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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.416   ! www         4: # $Id: grades.pm,v 1.415 2007/06/16 23:00:09 www 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.362     albertel   39: use Apache::lonmsg();
1.1       albertel   40: use Apache::Constants qw(:common);
1.167     sakharuk   41: use Apache::lonlocal;
1.386     raeburn    42: use Apache::lonenc;
1.170     albertel   43: use String::Similarity;
1.359     www        44: use LONCAPA;
                     45: 
1.315     bowersj2   46: use POSIX qw(floor);
1.87      www        47: 
                     48: my %oldessays=();
1.103     albertel   49: my %perm=();
1.1       albertel   50: 
1.68      ng         51: # ----- These first few routines are general use routines.----
1.44      ng         52: #
1.146     albertel   53: # --- Retrieve the parts from the metadata file.---
1.44      ng         54: sub getpartlist {
1.324     albertel   55:     my ($symb) = @_;
                     56:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.146     albertel   57:     my $partorder = &Apache::lonnet::metadata($url, 'partorder');
                     58:     my @parts;
                     59:     if ($partorder) {
                     60: 	for my $part (split (/,/,$partorder)) {
                     61: 	    if (!&Apache::loncommon::check_if_partid_hidden($part,$symb)) {
                     62: 		push(@parts, $part);
                     63: 	    }
                     64: 	}	    
                     65:     } else {
                     66: 	my $metadata = &Apache::lonnet::metadata($url, 'packages');
                     67: 	foreach (split(/\,/,$metadata)) {
                     68: 	    if ($_ =~ /^part_(.*)$/) {
                     69: 		if (!&Apache::loncommon::check_if_partid_hidden($1,$symb)) {
                     70: 		    push(@parts, $1);
                     71: 		}
                     72: 	    }
1.41      ng         73: 	}
1.16      albertel   74:     }
1.146     albertel   75:     my @stores;
                     76:     foreach my $part (@parts) {
                     77: 	my (@metakeys) = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                     78: 	foreach my $key (@metakeys) {
                     79: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                     80: 	}
                     81:     }
                     82:     return @stores;
1.2       albertel   83: }
                     84: 
1.44      ng         85: # --- Get the symbolic name of a problem and the url
1.324     albertel   86: sub get_symb {
1.173     albertel   87:     my ($request,$silent) = @_;
1.257     albertel   88:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                     89:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel   90:     if ($symb eq '') { 
                     91: 	if (!$silent) {
                     92: 	    $request->print("Unable to handle ambiguous references:$url:.");
                     93: 	    return ();
                     94: 	}
                     95:     }
1.324     albertel   96:     return ($symb);
1.32      ng         97: }
                     98: 
1.129     ng         99: #--- Format fullname, username:domain if different for display
                    100: #--- Use anywhere where the student names are listed
                    101: sub nameUserString {
                    102:     my ($type,$fullname,$uname,$udom) = @_;
                    103:     if ($type eq 'header') {
1.398     albertel  104: 	return '<b>&nbsp;Fullname&nbsp;</b><span class="LC_internal_info">(Username)</span>';
1.129     ng        105:     } else {
1.398     albertel  106: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    107: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        108:     }
                    109: }
                    110: 
1.44      ng        111: #--- Get the partlist and the response type for a given problem. ---
                    112: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        113: sub response_type {
1.324     albertel  114:     my ($symb) = shift;
1.377     albertel  115: 
                    116:     my $navmap = Apache::lonnavmaps::navmap->new();
                    117:     my $res = $navmap->getBySymb($symb);
                    118:     my $partlist = $res->parts();
1.392     albertel  119:     my %vPart = 
                    120: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  121:     my (%response_types,%handgrade);
                    122:     foreach my $part (@{ $partlist }) {
1.392     albertel  123: 	next if (%vPart && !exists($vPart{$part}));
                    124: 
1.377     albertel  125: 	my @types = $res->responseType($part);
                    126: 	my @ids = $res->responseIds($part);
                    127: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    128: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    129: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    130: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    131: 				     '.handgrade',$symb);
1.41      ng        132: 	}
                    133:     }
1.377     albertel  134:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        135: }
                    136: 
1.375     albertel  137: sub flatten_responseType {
                    138:     my ($responseType) = @_;
                    139:     my @part_response_id =
                    140: 	map { 
                    141: 	    my $part = $_;
                    142: 	    map {
                    143: 		[$part,$_]
                    144: 		} sort(keys(%{ $responseType->{$part} }));
                    145: 	} sort(keys(%$responseType));
                    146:     return @part_response_id;
                    147: }
                    148: 
1.207     albertel  149: sub get_display_part {
1.324     albertel  150:     my ($partID,$symb)=@_;
1.207     albertel  151:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    152:     if (defined($display) and $display ne '') {
1.398     albertel  153: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  154:     } else {
                    155: 	$display=$partID;
                    156:     }
                    157:     return $display;
                    158: }
1.269     raeburn   159: 
1.118     ng        160: #--- Show resource title
                    161: #--- and parts and response type
                    162: sub showResourceInfo {
1.324     albertel  163:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  164:     my $col=3;
                    165:     if ($checkboxes) { $col=4; }
1.398     albertel  166:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    167:     $result .='<table border="0">';
1.324     albertel  168:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        169:     my %resptype = ();
1.122     ng        170:     my $hdgrade='no';
1.154     albertel  171:     my %partsseen;
1.375     albertel  172:     foreach my $partID (sort keys(%$responseType)) {
                    173: 	foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
                    174: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    175: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    176: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    177: 	    $result.='<tr>';
                    178: 	    if ($checkboxes) {
                    179: 		if (exists($partsseen{$partID})) {
                    180: 		    $result.="<td>&nbsp;</td>";
                    181: 		} else {
1.401     albertel  182: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  183: 		}
                    184: 		$partsseen{$partID}=1;
1.154     albertel  185: 	    }
1.375     albertel  186: 	    my $display_part=&get_display_part($partID,$symb);
1.398     albertel  187: 	    $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
                    188: 		$resID.'</span></td>'.
1.375     albertel  189: 		'<td><b>Type: </b>'.$responsetype.'</td></tr>';
                    190: #	    '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
1.154     albertel  191: 	}
1.118     ng        192:     }
                    193:     $result.='</table>'."\n";
1.147     albertel  194:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        195: }
                    196: 
1.148     albertel  197: 
                    198: sub get_order {
                    199:     my ($partid,$respid,$symb,$uname,$udom)=@_;
                    200:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    201:     $url=&Apache::lonnet::clutter($url);
                    202:     my $subresult=&Apache::lonnet::ssi($url,
                    203: 				       ('grade_target' => 'analyze'),
                    204: 				       ('grade_domain' => $udom),
                    205: 				       ('grade_symb' => $symb),
                    206: 				       ('grade_courseid' => 
1.257     albertel  207: 					        $env{'request.course.id'}),
1.148     albertel  208: 				       ('grade_username' => $uname));
1.149     albertel  209:     (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
1.148     albertel  210:     my %analyze=&Apache::lonnet::str2hash($subresult);
                    211:     return ($analyze{"$partid.$respid.shown"});
                    212: }
1.118     ng        213: #--- Clean response type for display
1.335     albertel  214: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    215: #        response types only.
1.118     ng        216: sub cleanRecord {
1.336     albertel  217:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    218: 	$uname,$udom) = @_;
1.398     albertel  219:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  220:     if ($response =~ /^(option|rank)$/) {
                    221: 	my %answer=&Apache::lonnet::str2hash($answer);
                    222: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    223: 	my ($toprow,$bottomrow);
                    224: 	foreach my $foil (@$order) {
                    225: 	    if ($grading{$foil} == 1) {
                    226: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    227: 	    } else {
                    228: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    229: 	    }
1.398     albertel  230: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  231: 	}
                    232: 	return '<blockquote><table border="1">'.
                    233: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  234: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  235: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    236:     } elsif ($response eq 'match') {
                    237: 	my %answer=&Apache::lonnet::str2hash($answer);
                    238: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    239: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    240: 	my ($toprow,$middlerow,$bottomrow);
                    241: 	foreach my $foil (@$order) {
                    242: 	    my $item=shift(@items);
                    243: 	    if ($grading{$foil} == 1) {
                    244: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  245: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  246: 	    } else {
                    247: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  248: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  249: 	    }
1.398     albertel  250: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        251: 	}
1.126     ng        252: 	return '<blockquote><table border="1">'.
1.148     albertel  253: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  254: 	    '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
1.148     albertel  255: 	    $middlerow.'</tr>'.
1.398     albertel  256: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  257: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    258:     } elsif ($response eq 'radiobutton') {
                    259: 	my %answer=&Apache::lonnet::str2hash($answer);
                    260: 	my ($toprow,$bottomrow);
                    261: 	my $correct=($order->[0])+1;
                    262: 	for (my $i=1;$i<=$#$order;$i++) {
                    263: 	    my $foil=$order->[$i];
                    264: 	    if (exists($answer{$foil})) {
                    265: 		if ($i == $correct) {
                    266: 		    $toprow.='<td><b>true</b></td>';
                    267: 		} else {
                    268: 		    $toprow.='<td><i>true</i></td>';
                    269: 		}
                    270: 	    } else {
                    271: 		$toprow.='<td>false</td>';
                    272: 	    }
1.398     albertel  273: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  274: 	}
                    275: 	return '<blockquote><table border="1">'.
                    276: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  277: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  278: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    279:     } elsif ($response eq 'essay') {
1.257     albertel  280: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        281: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  282: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    283: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        284: 
1.257     albertel  285: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    286: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    287: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    288: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    289: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    290: 	    $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        291: 	}
1.166     albertel  292: 	$answer =~ s-\n-<br />-g;
                    293: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  294:     } elsif ( $response eq 'organic') {
                    295: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    296: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    297: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    298: 	return $result;
1.335     albertel  299:     } elsif ( $response eq 'Task') {
                    300: 	if ( $answer eq 'SUBMITTED') {
                    301: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  302: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  303: 	    return $result;
                    304: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    305: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    306: 			       keys(%{$record}));
                    307: 	    return join('<br />',($version,@matches));
                    308: 			       
                    309: 			       
                    310: 	} else {
                    311: 	    my $result =
                    312: 		'<p>'
                    313: 		.&mt('Overall result: [_1]',
                    314: 		     $record->{$version."resource.$respid.$partid.status"})
                    315: 		.'</p>';
                    316: 	    
                    317: 	    $result .= '<ul>';
                    318: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    319: 			     keys(%{$record}));
                    320: 	    foreach my $grade (sort(@grade)) {
                    321: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    322: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    323: 				     $dim, $record->{$grade}).
                    324: 			  '</li>';
                    325: 	    }
                    326: 	    $result.='</ul>';
                    327: 	    return $result;
                    328: 	}
                    329:        
1.122     ng        330:     }
1.118     ng        331:     return $answer;
                    332: }
                    333: 
                    334: #-- A couple of common js functions
                    335: sub commonJSfunctions {
                    336:     my $request = shift;
                    337:     $request->print(<<COMMONJSFUNCTIONS);
                    338: <script type="text/javascript" language="javascript">
                    339:     function radioSelection(radioButton) {
                    340: 	var selection=null;
                    341: 	if (radioButton.length > 1) {
                    342: 	    for (var i=0; i<radioButton.length; i++) {
                    343: 		if (radioButton[i].checked) {
                    344: 		    return radioButton[i].value;
                    345: 		}
                    346: 	    }
                    347: 	} else {
                    348: 	    if (radioButton.checked) return radioButton.value;
                    349: 	}
                    350: 	return selection;
                    351:     }
                    352: 
                    353:     function pullDownSelection(selectOne) {
                    354: 	var selection="";
                    355: 	if (selectOne.length > 1) {
                    356: 	    for (var i=0; i<selectOne.length; i++) {
                    357: 		if (selectOne[i].selected) {
                    358: 		    return selectOne[i].value;
                    359: 		}
                    360: 	    }
                    361: 	} else {
1.138     albertel  362:             // only one value it must be the selected one
                    363: 	    return selectOne.value;
1.118     ng        364: 	}
                    365:     }
                    366: </script>
                    367: COMMONJSFUNCTIONS
                    368: }
                    369: 
1.44      ng        370: #--- Dumps the class list with usernames,list of sections,
                    371: #--- section, ids and fullnames for each user.
                    372: sub getclasslist {
1.76      ng        373:     my ($getsec,$filterlist) = @_;
1.291     albertel  374:     my @getsec;
                    375:     if (!ref($getsec)) {
                    376: 	if ($getsec ne '' && $getsec ne 'all') {
                    377: 	    @getsec=($getsec);
                    378: 	}
                    379:     } else {
                    380: 	@getsec=@{$getsec};
                    381:     }
                    382:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
                    383: 
1.56      matthew   384:     my $classlist=&Apache::loncoursedata::get_classlist();
1.49      albertel  385:     # Bail out if we were unable to get the classlist
1.56      matthew   386:     return if (! defined($classlist));
                    387:     #
                    388:     my %sections;
                    389:     my %fullnames;
1.205     matthew   390:     foreach my $student (keys(%$classlist)) {
                    391:         my $end      = 
                    392:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    393:         my $start    = 
                    394:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    395:         my $id       = 
                    396:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    397:         my $section  = 
                    398:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    399:         my $fullname = 
                    400:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    401:         my $status   = 
                    402:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.76      ng        403: 	# filter students according to status selected
1.257     albertel  404: 	if ($filterlist && $env{'form.Status'} ne 'Any') {
                    405: 	    if ($env{'form.Status'} ne $status) {
1.205     matthew   406: 		delete ($classlist->{$student});
1.76      ng        407: 		next;
                    408: 	    }
                    409: 	}
1.205     matthew   410: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  411: 	if (&canview($section)) {
1.291     albertel  412: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  413: 		$sections{$section}++;
1.205     matthew   414: 		$fullnames{$student}=$fullname;
1.103     albertel  415: 	    } else {
1.205     matthew   416: 		delete($classlist->{$student});
1.103     albertel  417: 	    }
                    418: 	} else {
1.205     matthew   419: 	    delete($classlist->{$student});
1.103     albertel  420: 	}
1.44      ng        421:     }
                    422:     my %seen = ();
1.56      matthew   423:     my @sections = sort(keys(%sections));
                    424:     return ($classlist,\@sections,\%fullnames);
1.44      ng        425: }
                    426: 
1.103     albertel  427: sub canmodify {
                    428:     my ($sec)=@_;
                    429:     if ($perm{'mgr'}) {
                    430: 	if (!defined($perm{'mgr_section'})) {
                    431: 	    # can modify whole class
                    432: 	    return 1;
                    433: 	} else {
                    434: 	    if ($sec eq $perm{'mgr_section'}) {
                    435: 		#can modify the requested section
                    436: 		return 1;
                    437: 	    } else {
                    438: 		# can't modify the request section
                    439: 		return 0;
                    440: 	    }
                    441: 	}
                    442:     }
                    443:     #can't modify
                    444:     return 0;
                    445: }
                    446: 
                    447: sub canview {
                    448:     my ($sec)=@_;
                    449:     if ($perm{'vgr'}) {
                    450: 	if (!defined($perm{'vgr_section'})) {
                    451: 	    # can modify whole class
                    452: 	    return 1;
                    453: 	} else {
                    454: 	    if ($sec eq $perm{'vgr_section'}) {
                    455: 		#can modify the requested section
                    456: 		return 1;
                    457: 	    } else {
                    458: 		# can't modify the request section
                    459: 		return 0;
                    460: 	    }
                    461: 	}
                    462:     }
                    463:     #can't modify
                    464:     return 0;
                    465: }
                    466: 
1.44      ng        467: #--- Retrieve the grade status of a student for all the parts
                    468: sub student_gradeStatus {
1.324     albertel  469:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  470:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        471:     my %partstatus = ();
                    472:     foreach (@$partlist) {
1.128     ng        473: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        474: 	$status              = 'nothing' if ($status eq '');
                    475: 	$partstatus{$_}      = $status;
                    476: 	my $subkey           = "resource.$_.submitted_by";
                    477: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    478:     }
                    479:     return %partstatus;
                    480: }
                    481: 
1.45      ng        482: # hidden form and javascript that calls the form
                    483: # Use by verifyscript and viewgrades
                    484: # Shows a student's view of problem and submission
                    485: sub jscriptNform {
1.324     albertel  486:     my ($symb) = @_;
1.45      ng        487:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    488: 	'    function viewOneStudent(user,domain) {'."\n".
                    489: 	'	document.onestudent.student.value = user;'."\n".
                    490: 	'	document.onestudent.userdom.value = domain;'."\n".
                    491: 	'	document.onestudent.submit();'."\n".
                    492: 	'    }'."\n".
                    493: 	'</script>'."\n";
                    494:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
                    495: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.257     albertel  496: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    497: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
                    498: 	'<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.45      ng        499: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    500: 	'<input type="hidden" name="student" value="" />'."\n".
                    501: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    502: 	'</form>'."\n";
                    503:     return $jscript;
                    504: }
1.39      ng        505: 
1.315     bowersj2  506: # Given the score (as a number [0-1] and the weight) what is the final
                    507: # point value? This function will round to the nearest tenth, third,
                    508: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  509: sub compute_points {
1.315     bowersj2  510:     my ($score, $weight) = @_;
                    511:     
                    512:     my $tolerance = .00001;
                    513:     my $points = $score * $weight;
                    514: 
                    515:     # Check for nearness to 1/x.
                    516:     my $check_for_nearness = sub {
                    517:         my ($factor) = @_;
                    518:         my $num = ($points * $factor) + $tolerance;
                    519:         my $floored_num = floor($num);
1.316     albertel  520:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  521:             return $floored_num / $factor;
                    522:         }
                    523:         return $points;
                    524:     };
                    525: 
                    526:     $points = $check_for_nearness->(10);
                    527:     $points = $check_for_nearness->(3);
                    528:     $points = $check_for_nearness->(4);
                    529:     
                    530:     return $points;
                    531: }
                    532: 
1.44      ng        533: #------------------ End of general use routines --------------------
1.87      www       534: 
                    535: #
                    536: # Find most similar essay
                    537: #
                    538: 
                    539: sub most_similar {
                    540:     my ($uname,$udom,$uessay)=@_;
                    541: 
                    542: # ignore spaces and punctuation
                    543: 
                    544:     $uessay=~s/\W+/ /gs;
                    545: 
1.282     www       546: # ignore empty submissions (occuring when only files are sent)
                    547: 
                    548:     unless ($uessay=~/\w+/) { return ''; }
                    549: 
1.87      www       550: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       551:     my $limit=0.6;
1.87      www       552:     my $sname='';
                    553:     my $sdom='';
                    554:     my $scrsid='';
                    555:     my $sessay='';
                    556: # go through all essays ...
                    557:     foreach my $tkey (keys %oldessays) {
                    558: 	my ($tname,$tdom,$tcrsid)=split(/\./,$tkey);
                    559: # ... except the same student
1.88      www       560:         if (($tname ne $uname) || ($tdom ne $udom)) {
1.87      www       561: 	    my $tessay=$oldessays{$tkey};
                    562:             $tessay=~s/\W+/ /gs;
                    563: # String similarity gives up if not even limit
1.88      www       564:             my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       565: # Found one
                    566:             if ($tsimilar>$limit) {
                    567: 		$limit=$tsimilar;
                    568:                 $sname=$tname;
1.88      www       569:                 $sdom=$tdom;
1.87      www       570:                 $scrsid=$tcrsid;
                    571:                 $sessay=$oldessays{$tkey};
                    572:             }
                    573:         } 
                    574:     }
1.88      www       575:     if ($limit>0.6) {
1.87      www       576:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    577:     } else {
                    578:        return ('','','','',0);
                    579:     }
                    580: }
                    581: 
1.44      ng        582: #-------------------------------------------------------------------
                    583: 
                    584: #------------------------------------ Receipt Verification Routines
1.45      ng        585: #
1.44      ng        586: #--- Check whether a receipt number is valid.---
                    587: sub verifyreceipt {
                    588:     my $request  = shift;
                    589: 
1.257     albertel  590:     my $courseid = $env{'request.course.id'};
1.184     www       591:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  592: 	$env{'form.receipt'};
1.44      ng        593:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  594:     my ($symb)   = &get_symb($request);
1.44      ng        595: 
1.398     albertel  596:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
                    597: 	$receipt.'</h3></span>'."\n".
                    598: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
1.44      ng        599: 
                    600:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   601:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  602:     
                    603:     my $receiptparts=0;
1.390     albertel  604:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    605: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  606:     my $parts=['0'];
1.324     albertel  607:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.294     albertel  608:     foreach (sort 
                    609: 	     {
                    610: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    611: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    612: 		 }
                    613: 		 return $a cmp $b;
                    614: 	     } (keys(%$fullname))) {
1.44      ng        615: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  616: 	foreach my $part (@$parts) {
                    617: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
                    618: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
                    619: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
                    620: 		    '\')"; TARGET=_self>'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
                    621: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    622: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    623: 		if ($receiptparts) {
                    624: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    625: 		}
                    626: 		$contents.='</tr>'."\n";
                    627: 		
                    628: 		$matches++;
                    629: 	    }
1.44      ng        630: 	}
                    631:     }
                    632:     if ($matches == 0) {
                    633: 	$string = $title.'No match found for the above receipt.';
                    634:     } else {
1.324     albertel  635: 	$string = &jscriptNform($symb).$title.
1.44      ng        636: 	    'The above receipt matches the following student'.
                    637: 	    ($matches <= 1 ? '.' : 's.')."\n".
                    638: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                    639: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
                    640: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
                    641: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
1.177     albertel  642: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
                    643: 	if ($receiptparts) {
                    644: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
                    645: 	}
                    646: 	$string.='</tr>'."\n".$contents.
1.44      ng        647: 	    '</table></td></tr></table>'."\n";
                    648:     }
1.324     albertel  649:     return $string.&show_grading_menu_form($symb);
1.44      ng        650: }
                    651: 
                    652: #--- This is called by a number of programs.
                    653: #--- Called from the Grading Menu - View/Grade an individual student
                    654: #--- Also called directly when one clicks on the subm button 
                    655: #    on the problem page.
1.30      ng        656: sub listStudents {
1.41      ng        657:     my ($request) = shift;
1.49      albertel  658: 
1.324     albertel  659:     my ($symb) = &get_symb($request);
1.257     albertel  660:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    661:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    662:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                    663:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    664: 
                    665:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    666:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    667: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  668: 
1.398     albertel  669:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
                    670: 	' Submissions for a Student or a Group of Students</span></h3>';
1.118     ng        671: 
1.324     albertel  672:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  673: 
1.45      ng        674:     $request->print(<<LISTJAVASCRIPT);
                    675: <script type="text/javascript" language="javascript">
1.110     ng        676:     function checkSelect(checkBox) {
                    677: 	var ctr=0;
                    678: 	var sense="";
                    679: 	if (checkBox.length > 1) {
                    680: 	    for (var i=0; i<checkBox.length; i++) {
                    681: 		if (checkBox[i].checked) {
                    682: 		    ctr++;
                    683: 		}
                    684: 	    }
                    685: 	    sense = "a student or group of students";
                    686: 	} else {
                    687: 	    if (checkBox.checked) {
                    688: 		ctr = 1;
                    689: 	    }
                    690: 	    sense = "the student";
                    691: 	}
                    692: 	if (ctr == 0) {
1.126     ng        693: 	    alert("Please select "+sense+" before clicking on the Next button.");
1.110     ng        694: 	    return false;
                    695: 	}
                    696: 	document.gradesub.submit();
                    697:     }
                    698: 
                    699:     function reLoadList(formname) {
1.112     ng        700: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        701: 	formname.command.value = 'submission';
                    702: 	formname.submit();
                    703:     }
1.45      ng        704: </script>
                    705: LISTJAVASCRIPT
                    706: 
1.118     ng        707:     &commonJSfunctions($request);
1.41      ng        708:     $request->print($result);
1.39      ng        709: 
1.401     albertel  710:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    711:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  712:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
                    713: 	"\n".$table.
1.401     albertel  714: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.267     albertel  715: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
                    716: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
                    717: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
                    718: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
1.401     albertel  719: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
1.49      albertel  720: 	'&nbsp;<b>Submissions: </b>'."\n";
1.257     albertel  721:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.267     albertel  722: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
1.49      albertel  723:     }
1.110     ng        724: 
1.257     albertel  725:     my $saveStatus = $env{'form.Status'} eq '' ? 'Active' : $env{'form.Status'};
                    726:     $env{'form.Status'} = $saveStatus;
1.110     ng        727: 
1.267     albertel  728:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
                    729: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
                    730: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
1.348     bowersj2  731: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
                    732:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
                    733:         '<option value="1">Whole Points</option>'.
                    734:         '<option value=".5">Half Points</option>'.
1.349     albertel  735:         '<option value=".25">Quarter Points</option>'.
                    736:         '<option value=".1">Tenths of a Point</option>'.
1.348     bowersj2  737:         '</select>'.
                    738: 
1.45      ng        739: 	'<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
                    740: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  741: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    742: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    743: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    744: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.48      albertel  745: 	'<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
1.110     ng        746: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    747: 
1.257     albertel  748:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
                    749: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng        750:     } else {
                    751: 	$gradeTable.='<b>Student Status:</b> '.
                    752: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
                    753:     }
1.112     ng        754: 
1.126     ng        755:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    756: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
1.110     ng        757: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  758: 
                    759: # checkall buttons
                    760:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        761:     $gradeTable.='<input type="button" '."\n".
1.45      ng        762: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.249     albertel  763: 	'value="Next->" /> <br />'."\n";
                    764:     $gradeTable.=&check_buttons();
1.401     albertel  765:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
1.249     albertel  766:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
1.45      ng        767:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
1.110     ng        768: 	'<table border="0"><tr bgcolor="#e6ffff">';
                    769:     my $loop = 0;
                    770:     while ($loop < 2) {
1.126     ng        771: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
1.250     albertel  772: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
1.301     albertel  773: 	if ($env{'form.showgrading'} eq 'yes' 
                    774: 	    && $submitonly ne 'queued'
                    775: 	    && $submitonly ne 'all') {
1.110     ng        776: 	    foreach (sort(@$partlist)) {
1.324     albertel  777: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
1.207     albertel  778: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
                    779: 		    ' Status&nbsp;</b></td>';
1.110     ng        780: 	    }
1.301     albertel  781: 	} elsif ($submitonly eq 'queued') {
                    782: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
1.110     ng        783: 	}
                    784: 	$loop++;
1.126     ng        785: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        786:     }
1.45      ng        787:     $gradeTable.='</tr>'."\n";
1.41      ng        788: 
1.45      ng        789:     my $ctr = 0;
1.294     albertel  790:     foreach my $student (sort 
                    791: 			 {
                    792: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    793: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    794: 			     }
                    795: 			     return $a cmp $b;
                    796: 			 }
                    797: 			 (keys(%$fullname))) {
1.41      ng        798: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  799: 
1.110     ng        800: 	my %status = ();
1.301     albertel  801: 
                    802: 	if ($submitonly eq 'queued') {
                    803: 	    my %queue_status = 
                    804: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    805: 							$udom,$uname);
                    806: 	    next if (!defined($queue_status{'gradingqueue'}));
                    807: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    808: 	}
                    809: 
                    810: 	if ($env{'form.showgrading'} eq 'yes' 
                    811: 	    && $submitonly ne 'queued'
                    812: 	    && $submitonly ne 'all') {
1.324     albertel  813: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  814: 	    my $submitted = 0;
1.164     albertel  815: 	    my $graded = 0;
1.248     albertel  816: 	    my $incorrect = 0;
1.110     ng        817: 	    foreach (keys(%status)) {
1.145     albertel  818: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  819: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    820: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    821: 		
1.110     ng        822: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    823: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  824: 		    $submitted = 0;
1.150     albertel  825: 		    my ($part)=split(/\./,$partid);
1.110     ng        826: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  827: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        828: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    829: 		}
1.41      ng        830: 	    }
1.248     albertel  831: 	    
1.156     albertel  832: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    833: 				     $submitonly eq 'incorrect' ||
                    834: 				     $submitonly eq 'graded'));
1.248     albertel  835: 	    next if (!$graded && ($submitonly eq 'graded'));
                    836: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        837: 	}
1.34      ng        838: 
1.45      ng        839: 	$ctr++;
1.249     albertel  840: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    841: 
1.104     albertel  842: 	if ( $perm{'vgr'} eq 'F' ) {
1.110     ng        843: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
1.126     ng        844: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  845:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    846:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    847: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    848: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
                    849: 	       '&nbsp;'.$section.'</td>'."\n";
1.110     ng        850: 
1.257     albertel  851: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        852: 		foreach (sort keys(%status)) {
                    853: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  854: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        855: 		}
1.41      ng        856: 	    }
1.126     ng        857: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.110     ng        858: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
1.41      ng        859: 	}
                    860:     }
1.110     ng        861:     if ($ctr%2 ==1) {
1.126     ng        862: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel  863: 	    if ($env{'form.showgrading'} eq 'yes' 
                    864: 		&& $submitonly ne 'queued'
                    865: 		&& $submitonly ne 'all') {
1.110     ng        866: 		foreach (@$partlist) {
                    867: 		    $gradeTable.='<td>&nbsp;</td>';
                    868: 		}
1.301     albertel  869: 	    } elsif ($submitonly eq 'queued') {
                    870: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng        871: 	    }
                    872: 	$gradeTable.='</tr>';
                    873:     }
                    874: 
1.249     albertel  875:     $gradeTable.='</table></td></tr></table>'."\n".
1.45      ng        876: 	'<input type="button" '.
                    877: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng        878: 	'value="Next->" /></form>'."\n";
1.45      ng        879:     if ($ctr == 0) {
1.96      albertel  880: 	my $num_students=(scalar(keys(%$fullname)));
                    881: 	if ($num_students eq 0) {
1.398     albertel  882: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel  883: 	} else {
1.171     albertel  884: 	    my $submissions='submissions';
                    885: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                    886: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel  887: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel  888: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel  889: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel  890: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel  891: 	}
1.46      ng        892:     } elsif ($ctr == 1) {
                    893: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
1.45      ng        894:     }
1.324     albertel  895:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng        896:     $request->print($gradeTable);
1.44      ng        897:     return '';
1.10      ng        898: }
                    899: 
1.44      ng        900: #---- Called from the listStudents routine
1.249     albertel  901: 
                    902: sub check_script {
                    903:     my ($form, $type)=@_;
                    904:     my $chkallscript='<script type="text/javascript">
                    905:     function checkall() {
                    906:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    907:             ele = document.forms.'.$form.'.elements[i];
                    908:             if (ele.name == "'.$type.'") {
                    909:             document.forms.'.$form.'.elements[i].checked=true;
                    910:                                        }
                    911:         }
                    912:     }
                    913: 
                    914:     function checksec() {
                    915:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    916:             ele = document.forms.'.$form.'.elements[i];
                    917:            string = document.forms.'.$form.'.chksec.value;
                    918:            if
                    919:           (ele.value.indexOf(":::SECTION"+string)>0) {
                    920:               document.forms.'.$form.'.elements[i].checked=true;
                    921:             }
                    922:         }
                    923:     }
                    924: 
                    925: 
                    926:     function uncheckall() {
                    927:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    928:             ele = document.forms.'.$form.'.elements[i];
                    929:             if (ele.name == "'.$type.'") {
                    930:             document.forms.'.$form.'.elements[i].checked=false;
                    931:                                        }
                    932:         }
                    933:     }
                    934: 
                    935: </script>'."\n";
                    936:     return $chkallscript;
                    937: }
                    938: 
                    939: sub check_buttons {
                    940:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                    941:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                    942:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                    943:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                    944:     return $buttons;
                    945: }
                    946: 
1.44      ng        947: #     Displays the submissions for one student or a group of students
1.34      ng        948: sub processGroup {
1.41      ng        949:     my ($request)  = shift;
                    950:     my $ctr        = 0;
1.155     albertel  951:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng        952:     my $total      = scalar(@stuchecked)-1;
1.45      ng        953: 
1.396     banghart  954:     foreach my $student (@stuchecked) {
                    955: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel  956: 	$env{'form.student'}        = $uname;
                    957: 	$env{'form.userdom'}        = $udom;
                    958: 	$env{'form.fullname'}       = $fullname;
1.41      ng        959: 	&submission($request,$ctr,$total);
                    960: 	$ctr++;
                    961:     }
                    962:     return '';
1.35      ng        963: }
1.34      ng        964: 
1.44      ng        965: #------------------------------------------------------------------------------------
                    966: #
                    967: #-------------------------- Next few routines handles grading by student, essentially
                    968: #                           handles essay response type problem/part
                    969: #
                    970: #--- Javascript to handle the submission page functionality ---
                    971: sub sub_page_js {
                    972:     my $request = shift;
                    973:     $request->print(<<SUBJAVASCRIPT);
                    974: <script type="text/javascript" language="javascript">
1.71      ng        975:     function updateRadio(formname,id,weight) {
1.125     ng        976: 	var gradeBox = formname["GD_BOX"+id];
                    977: 	var radioButton = formname["RADVAL"+id];
                    978: 	var oldpts = formname["oldpts"+id].value;
1.72      ng        979: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng        980: 	gradeBox.value = pts;
                    981: 	var resetbox = false;
                    982: 	if (isNaN(pts) || pts < 0) {
                    983: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                    984: 	    for (var i=0; i<radioButton.length; i++) {
                    985: 		if (radioButton[i].checked) {
                    986: 		    gradeBox.value = i;
                    987: 		    resetbox = true;
                    988: 		}
                    989: 	    }
                    990: 	    if (!resetbox) {
                    991: 		formtextbox.value = "";
                    992: 	    }
                    993: 	    return;
1.44      ng        994: 	}
1.71      ng        995: 
                    996: 	if (pts > weight) {
                    997: 	    var resp = confirm("You entered a value ("+pts+
                    998: 			       ") greater than the weight for the part. Accept?");
                    999: 	    if (resp == false) {
1.125     ng       1000: 		gradeBox.value = oldpts;
1.71      ng       1001: 		return;
                   1002: 	    }
1.44      ng       1003: 	}
1.13      albertel 1004: 
1.71      ng       1005: 	for (var i=0; i<radioButton.length; i++) {
                   1006: 	    radioButton[i].checked=false;
                   1007: 	    if (pts == i && pts != "") {
                   1008: 		radioButton[i].checked=true;
                   1009: 	    }
                   1010: 	}
                   1011: 	updateSelect(formname,id);
1.125     ng       1012: 	formname["stores"+id].value = "0";
1.41      ng       1013:     }
1.5       albertel 1014: 
1.72      ng       1015:     function writeBox(formname,id,pts) {
1.125     ng       1016: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1017: 	if (checkSolved(formname,id) == 'update') {
                   1018: 	    gradeBox.value = pts;
                   1019: 	} else {
1.125     ng       1020: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1021: 	    gradeBox.value = oldpts;
1.125     ng       1022: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1023: 	    for (var i=0; i<radioButton.length; i++) {
                   1024: 		radioButton[i].checked=false;
1.72      ng       1025: 		if (i == oldpts) {
1.71      ng       1026: 		    radioButton[i].checked=true;
                   1027: 		}
                   1028: 	    }
1.41      ng       1029: 	}
1.125     ng       1030: 	formname["stores"+id].value = "0";
1.71      ng       1031: 	updateSelect(formname,id);
                   1032: 	return;
1.41      ng       1033:     }
1.44      ng       1034: 
1.71      ng       1035:     function clearRadBox(formname,id) {
                   1036: 	if (checkSolved(formname,id) == 'noupdate') {
                   1037: 	    updateSelect(formname,id);
                   1038: 	    return;
                   1039: 	}
1.125     ng       1040: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1041: 	for (var i=0; i<gradeSelect.length; i++) {
                   1042: 	    if (gradeSelect[i].selected) {
                   1043: 		var selectx=i;
                   1044: 	    }
                   1045: 	}
1.125     ng       1046: 	var stores = formname["stores"+id];
1.71      ng       1047: 	if (selectx == stores.value) { return };
1.125     ng       1048: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1049: 	gradeBox.value = "";
1.125     ng       1050: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1051: 	for (var i=0; i<radioButton.length; i++) {
                   1052: 	    radioButton[i].checked=false;
                   1053: 	}
                   1054: 	stores.value = selectx;
                   1055:     }
1.5       albertel 1056: 
1.71      ng       1057:     function checkSolved(formname,id) {
1.125     ng       1058: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1059: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1060: 	    if (!reply) {return "noupdate";}
1.120     ng       1061: 	    formname.overRideScore.value = 'yes';
1.41      ng       1062: 	}
1.71      ng       1063: 	return "update";
1.13      albertel 1064:     }
1.71      ng       1065: 
                   1066:     function updateSelect(formname,id) {
1.125     ng       1067: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1068: 	return;
1.41      ng       1069:     }
1.33      ng       1070: 
1.121     ng       1071: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1072:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1073: 	formname.gradeOpt.value = val;
1.71      ng       1074: 	if (val == "Save & Next") {
                   1075: 	    for (i=0;i<=total;i++) {
                   1076: 		for (j=0;j<parttot;j++) {
1.125     ng       1077: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1078: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1079: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1080: 			if (points == "") {
1.125     ng       1081: 			    var name = formname["name"+i].value;
1.129     ng       1082: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1083: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1084: 					       ", part "+partid+". Continue?");
1.71      ng       1085: 			    if (resp == false) {
1.125     ng       1086: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1087: 				return false;
                   1088: 			    }
                   1089: 			}
                   1090: 		    }
                   1091: 		    
                   1092: 		}
                   1093: 	    }
                   1094: 	    
                   1095: 	}
1.121     ng       1096: 	if (val == "Grade Student") {
                   1097: 	    formname.showgrading.value = "yes";
                   1098: 	    if (formname.Status.value == "") {
                   1099: 		formname.Status.value = "Active";
                   1100: 	    }
                   1101: 	    formname.studentNo.value = total;
                   1102: 	}
1.120     ng       1103: 	formname.submit();
                   1104:     }
                   1105: 
1.71      ng       1106: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1107:     function checkSubmitPage(formname,total) {
                   1108: 	noscore = new Array(100);
                   1109: 	var ptr = 0;
                   1110: 	for (i=1;i<total;i++) {
1.125     ng       1111: 	    var partid = formname["q_"+i].value;
1.127     ng       1112: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1113: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1114: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1115: 		if (points == "" && status != "correct_by_student") {
                   1116: 		    noscore[ptr] = i;
                   1117: 		    ptr++;
                   1118: 		}
                   1119: 	    }
                   1120: 	}
                   1121: 	if (ptr != 0) {
                   1122: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1123: 	    var prolist = "";
                   1124: 	    if (ptr == 1) {
                   1125: 		prolist = noscore[0];
                   1126: 	    } else {
                   1127: 		var i = 0;
                   1128: 		while (i < ptr-1) {
                   1129: 		    prolist += noscore[i]+", ";
                   1130: 		    i++;
                   1131: 		}
                   1132: 		prolist += "and "+noscore[i];
                   1133: 	    }
                   1134: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1135: 	    if (resp == false) {
                   1136: 		return false;
                   1137: 	    }
                   1138: 	}
1.45      ng       1139: 
1.71      ng       1140: 	formname.submit();
                   1141:     }
                   1142: </script>
                   1143: SUBJAVASCRIPT
                   1144: }
1.45      ng       1145: 
1.71      ng       1146: #--- javascript for essay type problem --
                   1147: sub sub_page_kw_js {
                   1148:     my $request = shift;
1.80      ng       1149:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1150:     &commonJSfunctions($request);
1.350     albertel 1151: 
1.351     albertel 1152:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1153:     <script text="text/javascript">
                   1154:     function checkInput() {
                   1155:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1156:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1157:       var usrctr = document.msgcenter.usrctr.value;
                   1158:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1159:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1160: 
                   1161:       var msgchk = "";
                   1162:       if (document.msgcenter.subchk.checked) {
                   1163:          msgchk = "msgsub,";
                   1164:       }
                   1165:       var includemsg = 0;
                   1166:       for (var i=1; i<=nmsg; i++) {
                   1167:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1168:           var frmmsg = document.msgcenter["msg"+i];
                   1169:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1170:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1171:           showflg.value = "1";
                   1172:           var chkbox = document.msgcenter["msgn"+i];
                   1173:           if (chkbox.checked) {
                   1174:              msgchk += "savemsg"+i+",";
                   1175:              includemsg = 1;
                   1176:           }
                   1177:       }
                   1178:       if (document.msgcenter.newmsgchk.checked) {
                   1179:          msgchk += "newmsg"+usrctr;
                   1180:          includemsg = 1;
                   1181:       }
                   1182:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1183:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1184:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1185:       includemsg.value = msgchk;
                   1186: 
                   1187:       self.close()
                   1188: 
                   1189:     }
                   1190:     </script>
                   1191: INNERJS
                   1192: 
1.351     albertel 1193:     my $inner_js_highlight_central=<<INNERJS;
                   1194:  <script type="text/javascript">
                   1195:     function updateChoice(flag) {
                   1196:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1197:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1198:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1199:       opener.document.SCORE.refresh.value = "on";
                   1200:       if (opener.document.SCORE.keywords.value!=""){
                   1201:          opener.document.SCORE.submit();
                   1202:       }
                   1203:       self.close()
                   1204:     }
                   1205: </script>
                   1206: INNERJS
                   1207: 
                   1208:     my $start_page_msg_central = 
                   1209:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1210: 				       {'js_ready'  => 1,
                   1211: 					'only_body' => 1,
                   1212: 					'bgcolor'   =>'#FFFFFF',});
                   1213:     my $end_page_msg_central = 
                   1214: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1215: 
                   1216: 
                   1217:     my $start_page_highlight_central = 
                   1218:         &Apache::loncommon::start_page('Highlight Central',
                   1219: 				       $inner_js_highlight_central,
1.350     albertel 1220: 				       {'js_ready'  => 1,
                   1221: 					'only_body' => 1,
                   1222: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1223:     my $end_page_highlight_central = 
1.350     albertel 1224: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1225: 
1.219     www      1226:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1227:     $docopen=~s/^document\.//;
1.71      ng       1228:     $request->print(<<SUBJAVASCRIPT);
                   1229: <script type="text/javascript" language="javascript">
1.45      ng       1230: 
1.44      ng       1231: //===================== Show list of keywords ====================
1.122     ng       1232:   function keywords(formname) {
                   1233:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1234:     if (nret==null) return;
1.122     ng       1235:     formname.keywords.value = nret;
1.44      ng       1236: 
1.122     ng       1237:     if (formname.keywords.value != "") {
1.128     ng       1238: 	formname.refresh.value = "on";
1.122     ng       1239: 	formname.submit();
1.44      ng       1240:     }
                   1241:     return;
                   1242:   }
                   1243: 
                   1244: //===================== Script to view submitted by ==================
                   1245:   function viewSubmitter(submitter) {
                   1246:     document.SCORE.refresh.value = "on";
                   1247:     document.SCORE.NCT.value = "1";
                   1248:     document.SCORE.unamedom0.value = submitter;
                   1249:     document.SCORE.submit();
                   1250:     return;
                   1251:   }
                   1252: 
                   1253: //===================== Script to add keyword(s) ==================
                   1254:   function getSel() {
                   1255:     if (document.getSelection) txt = document.getSelection();
                   1256:     else if (document.selection) txt = document.selection.createRange().text;
                   1257:     else return;
                   1258:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1259:     if (cleantxt=="") {
1.46      ng       1260: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1261: 	return;
                   1262:     }
                   1263:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1264:     if (nret==null) return;
1.127     ng       1265:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1266:     if (document.SCORE.keywords.value != "") {
1.127     ng       1267: 	document.SCORE.refresh.value = "on";
1.44      ng       1268: 	document.SCORE.submit();
                   1269:     }
                   1270:     return;
                   1271:   }
                   1272: 
                   1273: //====================== Script for composing message ==============
1.80      ng       1274:    // preload images
                   1275:    img1 = new Image();
                   1276:    img1.src = "$iconpath/mailbkgrd.gif";
                   1277:    img2 = new Image();
                   1278:    img2.src = "$iconpath/mailto.gif";
                   1279: 
1.44      ng       1280:   function msgCenter(msgform,usrctr,fullname) {
                   1281:     var Nmsg  = msgform.savemsgN.value;
                   1282:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1283:     var subject = msgform.msgsub.value;
1.127     ng       1284:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1285:     re = /msgsub/;
                   1286:     var shwsel = "";
                   1287:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1288:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1289:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1290:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1291: 	var testmsg = "savemsg"+i+",";
                   1292: 	re = new RegExp(testmsg,"g");
1.44      ng       1293: 	shwsel = "";
                   1294: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1295: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1296: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1297: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1298: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1299:     }
1.125     ng       1300:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1301:     shwsel = "";
                   1302:     re = /newmsg/;
                   1303:     if (re.test(msgchk)) { shwsel = "checked" }
                   1304:     newMsg(newmsg,shwsel);
                   1305:     msgTail(); 
                   1306:     return;
                   1307:   }
                   1308: 
1.123     ng       1309:   function checkEntities(strx) {
                   1310:     if (strx.length == 0) return strx;
                   1311:     var orgStr = ["&", "<", ">", '"']; 
                   1312:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1313:     var counter = 0;
                   1314:     while (counter < 4) {
                   1315: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1316: 	counter++;
                   1317:     }
                   1318:     return strx;
                   1319:   }
                   1320: 
                   1321:   function strReplace(strx, orgStr, newStr) {
                   1322:     return strx.split(orgStr).join(newStr);
                   1323:   }
                   1324: 
1.44      ng       1325:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1326:     var height = 70*Nmsg+250;
1.44      ng       1327:     var scrollbar = "no";
                   1328:     if (height > 600) {
                   1329: 	height = 600;
                   1330: 	scrollbar = "yes";
                   1331:     }
1.118     ng       1332:     var xpos = (screen.width-600)/2;
                   1333:     xpos = (xpos < 0) ? '0' : xpos;
                   1334:     var ypos = (screen.height-height)/2-30;
                   1335:     ypos = (ypos < 0) ? '0' : ypos;
                   1336: 
1.206     albertel 1337:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1338:     pWin.focus();
                   1339:     pDoc = pWin.document;
1.219     www      1340:     pDoc.$docopen;
1.351     albertel 1341:     pDoc.write('$start_page_msg_central');
1.76      ng       1342: 
                   1343:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1344:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.398     albertel 1345:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
1.76      ng       1346: 
                   1347:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1348:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1349:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1.44      ng       1350: }
                   1351:     function displaySubject(msg,shwsel) {
1.76      ng       1352:     pDoc = pWin.document;
                   1353:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1354:     pDoc.write("<td>Subject</td>");
                   1355:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1356:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1.44      ng       1357: }
                   1358: 
1.72      ng       1359:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1360:     pDoc = pWin.document;
                   1361:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1362:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
                   1363:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1364:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1.44      ng       1365: }
                   1366: 
                   1367:   function newMsg(newmsg,shwsel) {
1.76      ng       1368:     pDoc = pWin.document;
                   1369:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1370:     pDoc.write("<td align=\\"center\\">New</td>");
                   1371:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1372:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1.44      ng       1373: }
                   1374: 
                   1375:   function msgTail() {
1.76      ng       1376:     pDoc = pWin.document;
                   1377:     pDoc.write("</table>");
                   1378:     pDoc.write("</td></tr></table>&nbsp;");
                   1379:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1380:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1381:     pDoc.write("</form>");
1.351     albertel 1382:     pDoc.write('$end_page_msg_central');
1.128     ng       1383:     pDoc.close();
1.44      ng       1384: }
                   1385: 
                   1386: //====================== Script for keyword highlight options ==============
                   1387:   function kwhighlight() {
                   1388:     var kwclr    = document.SCORE.kwclr.value;
                   1389:     var kwsize   = document.SCORE.kwsize.value;
                   1390:     var kwstyle  = document.SCORE.kwstyle.value;
                   1391:     var redsel = "";
                   1392:     var grnsel = "";
                   1393:     var blusel = "";
                   1394:     if (kwclr=="red")   {var redsel="checked"};
                   1395:     if (kwclr=="green") {var grnsel="checked"};
                   1396:     if (kwclr=="blue")  {var blusel="checked"};
                   1397:     var sznsel = "";
                   1398:     var sz1sel = "";
                   1399:     var sz2sel = "";
                   1400:     if (kwsize=="0")  {var sznsel="checked"};
                   1401:     if (kwsize=="+1") {var sz1sel="checked"};
                   1402:     if (kwsize=="+2") {var sz2sel="checked"};
                   1403:     var synsel = "";
                   1404:     var syisel = "";
                   1405:     var sybsel = "";
                   1406:     if (kwstyle=="")    {var synsel="checked"};
                   1407:     if (kwstyle=="<i>") {var syisel="checked"};
                   1408:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1409:     highlightCentral();
                   1410:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1411:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1412:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1413:     highlightend();
                   1414:     return;
                   1415:   }
                   1416: 
                   1417:   function highlightCentral() {
1.76      ng       1418: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1419:     var xpos = (screen.width-400)/2;
                   1420:     xpos = (xpos < 0) ? '0' : xpos;
                   1421:     var ypos = (screen.height-330)/2-30;
                   1422:     ypos = (ypos < 0) ? '0' : ypos;
                   1423: 
1.206     albertel 1424:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1425:     hwdWin.focus();
                   1426:     var hDoc = hwdWin.document;
1.219     www      1427:     hDoc.$docopen;
1.351     albertel 1428:     hDoc.write('$start_page_highlight_central');
1.76      ng       1429:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.398     albertel 1430:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
1.76      ng       1431: 
                   1432:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1433:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1434:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1.44      ng       1435:   }
                   1436: 
                   1437:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1438:     var hDoc = hwdWin.document;
                   1439:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1440:     hDoc.write("<td align=\\"left\\">");
                   1441:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
                   1442:     hDoc.write("<td align=\\"left\\">");
                   1443:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
                   1444:     hDoc.write("<td align=\\"left\\">");
                   1445:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
                   1446:     hDoc.write("</tr>");
1.44      ng       1447:   }
                   1448: 
                   1449:   function highlightend() { 
1.76      ng       1450:     var hDoc = hwdWin.document;
                   1451:     hDoc.write("</table>");
                   1452:     hDoc.write("</td></tr></table>&nbsp;");
                   1453:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1454:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1455:     hDoc.write("</form>");
1.351     albertel 1456:     hDoc.write('$end_page_highlight_central');
1.128     ng       1457:     hDoc.close();
1.44      ng       1458:   }
                   1459: 
                   1460: </script>
                   1461: SUBJAVASCRIPT
                   1462: }
                   1463: 
1.349     albertel 1464: sub get_increment {
1.348     bowersj2 1465:     my $increment = $env{'form.increment'};
                   1466:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1467:         $increment != .1) {
                   1468:         $increment = 1;
                   1469:     }
                   1470:     return $increment;
                   1471: }
                   1472: 
1.71      ng       1473: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1474: sub gradeBox {
1.322     albertel 1475:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1476:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1477: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1478: 	'/check.gif" height="16" border="0" />';
                   1479:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
                   1480:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
1.398     albertel 1481: 		  '<span class="LC_info">problem weight assigned by computer</span>');
1.71      ng       1482:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1483:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1484: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1485:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.324     albertel 1486:     my $display_part=&get_display_part($partid,$symb);
1.270     albertel 1487:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1488: 				       [$partid]);
                   1489:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1490:     if ($last_resets{$partid}) {
                   1491:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1492:     }
1.71      ng       1493:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1494: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1495:     my $ctr = 0;
1.348     bowersj2 1496:     my $thisweight = 0;
1.349     albertel 1497:     my $increment = &get_increment();
1.71      ng       1498:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1499:     while ($thisweight<=$wgt) {
1.381     albertel 1500: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1501: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1502: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1503: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1504: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1505:         $thisweight += $increment;
1.71      ng       1506: 	$ctr++;
                   1507:     }
                   1508:     $result.='</tr></table>';
                   1509:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1510:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1511: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1512: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1513: 	$wgt.')" /></td>'."\n";
                   1514:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1515: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1516: 	' </td><td>'."\n";
                   1517:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1518: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1519:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1520: 	$result.='<option></option>'.
1.401     albertel 1521: 	    '<option selected="selected">excused</option>';
1.71      ng       1522:     } else {
1.401     albertel 1523: 	$result.='<option selected="selected"></option>'.
1.125     ng       1524: 	    '<option>excused</option>';
1.71      ng       1525:     }
1.125     ng       1526:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1527:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1528:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1529: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1530: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1531: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1532:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1533:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1534:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1535:         $aggtries.'" />'."\n";
1.71      ng       1536:     $result.='</td></tr></table>'."\n";
1.323     banghart 1537:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1538:     return $result;
                   1539: }
1.322     albertel 1540: 
                   1541: sub handback_box {
1.323     banghart 1542:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1543:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1544:     my (@respids);
1.375     albertel 1545:      my @part_response_id = &flatten_responseType($responseType);
                   1546:     foreach my $part_response_id (@part_response_id) {
                   1547:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1548:         if ($part eq $partid) {
1.375     albertel 1549:             push(@respids,$resp);
1.323     banghart 1550:         }
                   1551:     }
1.318     banghart 1552:     my $result;
1.323     banghart 1553:     foreach my $respid (@respids) {
1.322     albertel 1554: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1555: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1556: 	next if (!@$files);
                   1557: 	my $file_counter = 1;
1.313     banghart 1558: 	foreach my $file (@$files) {
1.368     banghart 1559: 	    if ($file =~ /\/portfolio\//) {
                   1560:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1561:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1562:     	        $file_disp = "$name.$ext";
                   1563:     	        $file = $file_path.$file_disp;
                   1564:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1565:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1566:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1567:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.369     banghart 1568:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1.368     banghart 1569:     	        $file_counter++;
                   1570: 	    }
1.322     albertel 1571: 	}
1.313     banghart 1572:     }
1.318     banghart 1573:     return $result;    
1.71      ng       1574: }
1.44      ng       1575: 
1.58      albertel 1576: sub show_problem {
1.382     albertel 1577:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1578:     my $rendered;
1.382     albertel 1579:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1580:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1581:     if ($mode eq 'both' or $mode eq 'text') {
                   1582: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1583: 						       $env{'request.course.id'},
                   1584: 						       undef,\%form);
1.144     albertel 1585:     }
1.58      albertel 1586:     if ($removeform) {
                   1587: 	$rendered=~s|<form(.*?)>||g;
                   1588: 	$rendered=~s|</form>||g;
1.374     albertel 1589: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1590:     }
1.144     albertel 1591:     my $companswer;
                   1592:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1593: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1594: 	$companswer=
                   1595: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1596: 						    $env{'request.course.id'},
                   1597: 						    %form);
1.144     albertel 1598:     }
1.58      albertel 1599:     if ($removeform) {
                   1600: 	$companswer=~s|<form(.*?)>||g;
                   1601: 	$companswer=~s|</form>||g;
1.144     albertel 1602: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1603:     }
                   1604:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1605:     $result.='<table border="0" width="100%">';
1.144     albertel 1606:     if ($viewon) {
                   1607: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1608: 	if ($mode eq 'both' or $mode eq 'text') {
                   1609: 	    $result.='View of the problem - ';
                   1610: 	} else {
                   1611: 	    $result.='Correct answer: ';
                   1612: 	}
1.257     albertel 1613: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1614:     }
                   1615:     if ($mode eq 'both') {
                   1616: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1617: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1618:     } elsif ($mode eq 'text') {
                   1619: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1620:     } elsif ($mode eq 'answer') {
                   1621: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1622:     }
1.58      albertel 1623:     $result.='</td></tr></table>';
                   1624:     $result.='</td></tr></table><br />';
1.71      ng       1625:     return $result;
1.58      albertel 1626: }
1.397     albertel 1627: 
1.396     banghart 1628: sub files_exist {
                   1629:     my ($r, $symb) = @_;
                   1630:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1631: 
1.396     banghart 1632:     foreach my $student (@students) {
                   1633:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1634:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1635: 					      $udom,$uname);
1.396     banghart 1636:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1637:         foreach my $submission (@$string) {
                   1638:             my ($partid,$respid) =
                   1639: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1640:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1641: 					   \%record);
                   1642:             return 1 if (@$files);
1.396     banghart 1643:         }
                   1644:     }
1.397     albertel 1645:     return 0;
1.396     banghart 1646: }
1.397     albertel 1647: 
1.394     banghart 1648: sub download_all_link {
                   1649:     my ($r,$symb) = @_;
1.395     albertel 1650:     my $all_students = 
                   1651: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1652: 
                   1653:     my $parts =
                   1654: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1655: 
1.394     banghart 1656:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1657:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1658:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1659:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1660:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1661: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1662:     return
                   1663: }
1.395     albertel 1664: 
1.44      ng       1665: # --------------------------- show submissions of a student, option to grade 
                   1666: sub submission {
                   1667:     my ($request,$counter,$total) = @_;
                   1668: 
1.257     albertel 1669:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1670:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1671:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1672:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.41      ng       1673: 
1.324     albertel 1674:     my $symb = &get_symb($request); 
                   1675:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1676: 
                   1677:     if (!&canview($usec)) {
1.398     albertel 1678: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1679: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1680: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1681: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1682: 	return;
                   1683:     }
                   1684: 
1.257     albertel 1685:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1686:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1687:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1688:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1689:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1690: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1691: 	'/check.gif" height="16" border="0" />';
1.41      ng       1692: 
                   1693:     # header info
                   1694:     if ($counter == 0) {
                   1695: 	&sub_page_js($request);
1.257     albertel 1696: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1697: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1698: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1699: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1700: 	    &download_all_link($request, $symb);
                   1701: 	}
1.398     albertel 1702: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
                   1703: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1.118     ng       1704: 
1.257     albertel 1705: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1706: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1707: 		$checkIcon.' symbol.'."\n";
                   1708: 	    $request->print($checkMark);
                   1709: 	}
1.41      ng       1710: 
1.44      ng       1711: 	# option to display problem, only once else it cause problems 
                   1712:         # with the form later since the problem has a form.
1.257     albertel 1713: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1714: 	    my $mode;
1.257     albertel 1715: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1716: 		$mode='both';
1.257     albertel 1717: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1718: 		$mode='text';
1.257     albertel 1719: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1720: 		$mode='answer';
                   1721: 	    }
1.329     albertel 1722: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1723: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1724: 	}
                   1725: 	
1.44      ng       1726: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1727:         # if this subroutine has been called once.
1.41      ng       1728: 	my %keyhash = ();
1.257     albertel 1729: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1730: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1731: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1732: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1733: 
1.257     albertel 1734: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1735: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1736: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1737: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1738: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1739: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1740: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1741: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1742: 	}
1.257     albertel 1743: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.44      ng       1744: 
1.303     banghart 1745: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1746: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1747: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
                   1748: 			'<input type="hidden" name="Status"     value="'.$env{'form.Status'}.'" />'."\n".
1.120     ng       1749: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1750: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1751: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1752: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1753: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.41      ng       1754: 			'<input type="hidden" name="symb"       value="'.$symb.'" />'."\n".
1.257     albertel 1755: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1756: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1757: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1758: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.326     albertel 1759: 			'<input type="hidden" name="section"    value="'.$env{'form.section'}.'" />'."\n".
                   1760: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1761: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1762: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1763: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1764: 	if ($env{'form.handgrade'} eq 'yes') {
                   1765: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1766: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1767: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1768: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1769: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1770: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1771: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1772: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1773: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1774: 	    }
1.123     ng       1775: 	}
1.41      ng       1776: 	
                   1777: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1778: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1779: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1780: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1781: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1782: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1783: 		'" />'."\n".
                   1784: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1785: 	    $cts++;
                   1786: 	}
                   1787: 	$request->print($prnmsg);
1.32      ng       1788: 
1.257     albertel 1789: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1790: #
                   1791: # Print out the keyword options line
                   1792: #
1.41      ng       1793: 	    $request->print(<<KEYWORDS);
1.38      ng       1794: &nbsp;<b>Keyword Options:</b>&nbsp;
1.122     ng       1795: <a href="javascript:keywords(document.SCORE)"; TARGET=_self>List</a>&nbsp; &nbsp;
1.38      ng       1796: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1797:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
                   1798: <a href="javascript:kwhighlight()"; TARGET=_self>Highlight Attribute</a><br /><br />
                   1799: KEYWORDS
1.88      www      1800: #
                   1801: # Load the other essays for similarity check
                   1802: #
1.324     albertel 1803:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1804: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1805: 	    $apath=&escape($apath);
1.88      www      1806: 	    $apath=~s/\W/\_/gs;
                   1807: 	    %oldessays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1808:         }
                   1809:     }
1.44      ng       1810: 
1.257     albertel 1811:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.71      ng       1812: 	$request->print('<br /><br /><br />') if ($counter > 0);
1.144     albertel 1813: 	my $mode;
1.257     albertel 1814: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1815: 	    $mode='both';
1.257     albertel 1816: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1817: 	    $mode='text';
1.257     albertel 1818: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1819: 	    $mode='answer';
                   1820: 	}
1.329     albertel 1821: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1822: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1823:     }
1.144     albertel 1824: 
1.257     albertel 1825:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1826:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1827: 
1.44      ng       1828:     # Display student info
1.41      ng       1829:     $request->print(($counter == 0 ? '' : '<br />'));
1.326     albertel 1830:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
                   1831: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1.44      ng       1832: 
1.257     albertel 1833:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1.45      ng       1834:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1835: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1836: 
1.118     ng       1837:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.45      ng       1838:     my @col_fullnames;
1.56      matthew  1839:     my ($classlist,$fullname);
1.257     albertel 1840:     if ($env{'form.handgrade'} eq 'yes') {
1.80      ng       1841: 	($classlist,undef,$fullname) = &getclasslist('all','0');
1.41      ng       1842: 	for (keys (%$handgrade)) {
1.44      ng       1843: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1.57      matthew  1844: 					    '.maxcollaborators',
                   1845:                                             $symb,$udom,$uname);
                   1846: 	    next if ($ncol <= 0);
                   1847:             s/\_/\./g;
                   1848:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
1.86      ng       1849:             my @goodcollaborators = ();
                   1850:             my @badcollaborators  = ();
                   1851: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
                   1852: 		$_ =~ s/[\$\^\(\)]//g;
                   1853: 		next if ($_ eq '');
1.80      ng       1854: 		my ($co_name,$co_dom) = split /\@|:/,$_;
1.86      ng       1855: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1.80      ng       1856: 		next if ($co_name eq $uname && $co_dom eq $udom);
1.86      ng       1857: 		# Doing this grep allows 'fuzzy' specification
                   1858: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
                   1859: 		if (! scalar(@Matches)) {
                   1860: 		    push @badcollaborators,$_;
                   1861: 		} else {
                   1862: 		    push @goodcollaborators, @Matches;
                   1863: 		}
1.80      ng       1864: 	    }
1.86      ng       1865:             if (scalar(@goodcollaborators) != 0) {
1.57      matthew  1866:                 $result.='<b>Collaborators: </b>';
1.86      ng       1867:                 foreach (@goodcollaborators) {
                   1868: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
                   1869: 		    push @col_fullnames, $givenn.' '.$lastname;
                   1870: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
                   1871: 		}
1.57      matthew  1872:                 $result.='<br />'."\n";
1.150     albertel 1873: 		my ($part)=split(/\./,$_);
1.86      ng       1874: 		$result.='<input type="hidden" name="collaborator'.$counter.
1.150     albertel 1875: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
                   1876: 		    "\n";
1.86      ng       1877: 	    }
                   1878: 	    if (scalar(@badcollaborators) > 0) {
                   1879: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1880: 		$result.='This student has submitted ';
                   1881: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
                   1882: 		$result .= ': '.join(', ',@badcollaborators);
                   1883: 		$result .= '</td></tr></table>';
                   1884: 	    }         
                   1885: 	    if (scalar(@badcollaborators > $ncol)) {
                   1886: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1887: 		$result .= 'This student has submitted too many '.
                   1888: 		    'collaborators.  Maximum is '.$ncol.'.';
                   1889: 		$result .= '</td></tr></table>';
                   1890: 	    }
1.41      ng       1891: 	}
                   1892:     }
1.44      ng       1893:     $request->print($result."\n");
1.33      ng       1894: 
1.44      ng       1895:     # print student answer/submission
                   1896:     # Options are (1) Handgaded submission only
                   1897:     #             (2) Last submission, includes submission that is not handgraded 
                   1898:     #                  (for multi-response type part)
                   1899:     #             (3) Last submission plus the parts info
                   1900:     #             (4) The whole record for this student
1.257     albertel 1901:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 1902: 	my ($string,$timestamp)= &get_last_submission(\%record);
                   1903: 	my $lastsubonly=''.
                   1904: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
                   1905: 	     $$timestamp)."</td></tr>\n";
                   1906: 	if ($$timestamp eq '') {
                   1907: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
                   1908: 	} else {
                   1909: 	    my %seenparts;
1.375     albertel 1910: 	    my @part_response_id = &flatten_responseType($responseType);
                   1911: 	    foreach my $part (@part_response_id) {
1.393     albertel 1912: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   1913: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   1914: 
1.375     albertel 1915: 		my ($partid,$respid) = @{ $part };
1.324     albertel 1916: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 1917: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 1918: 		    if (exists($seenparts{$partid})) { next; }
                   1919: 		    $seenparts{$partid}=1;
1.207     albertel 1920: 		    my $submitby='<b>Part:</b> '.$display_part.
                   1921: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 1922: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 1923: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.151     albertel 1924: 			'\')"; TARGET=_self>'.
1.257     albertel 1925: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 1926: 		    $request->print($submitby);
                   1927: 		    next;
                   1928: 		}
                   1929: 		my $responsetype = $responseType->{$partid}->{$respid};
                   1930: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.207     albertel 1931: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1.398     albertel 1932: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   1933: 			' )</span>&nbsp; &nbsp;'.
                   1934: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1.151     albertel 1935: 		    next;
                   1936: 		}
                   1937: 		foreach (@$string) {
                   1938: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1.375     albertel 1939: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.151     albertel 1940: 		    my ($ressub,$subval) = split(/:/,$_,2);
                   1941: 		    # Similarity check
                   1942: 		    my $similar='';
1.257     albertel 1943: 		    if($env{'form.checkPlag'}){
1.151     albertel 1944: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   1945: 			    &most_similar($uname,$udom,$subval);
                   1946: 			if ($osim) {
                   1947: 			    $osim=int($osim*100.0);
1.398     albertel 1948: 			    $similar="<hr /><h3><span class=\"LC_warning\">Essay".
1.151     albertel 1949: 				" is $osim% similar to an essay by ".
                   1950: 				&Apache::loncommon::plainname($oname,$odom).
1.398     albertel 1951: 				'</span></h3><blockquote><i>'.
1.151     albertel 1952: 				&keywords_highlight($oessay).
                   1953: 				'</i></blockquote><hr />';
                   1954: 			}
1.150     albertel 1955: 		    }
1.151     albertel 1956: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 1957: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   1958: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 1959: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 1960: 			my $display_part=&get_display_part($partid,$symb);
1.403     albertel 1961: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   1962: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 1963: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 1964: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   1965: 			if (@$files) {
1.398     albertel 1966: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1.303     banghart 1967: 			    my $file_counter = 0;
1.313     banghart 1968: 			    foreach my $file (@$files) {
1.303     banghart 1969: 			        $file_counter ++;
1.232     albertel 1970: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 1971: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 1972: 			    }
1.236     albertel 1973: 			    $lastsubonly.='<br />';
1.41      ng       1974: 			}
1.151     albertel 1975: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   1976: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   1977: 					 $respid,\%record,$order);
                   1978: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       1979: 		    }
                   1980: 		}
                   1981: 	    }
1.151     albertel 1982: 	}
                   1983: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   1984: 	$request->print($lastsubonly);
1.257     albertel 1985:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 1986: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 1987: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 1988:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       1989: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 1990: 								 $env{'request.course.id'},
1.44      ng       1991: 								 $last,'.submission',
                   1992: 								 'Apache::grades::keywords_highlight'));
1.41      ng       1993:     }
1.120     ng       1994: 
1.121     ng       1995:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   1996: 	.$udom.'" />'."\n");
1.41      ng       1997:     
1.44      ng       1998:     # return if view submission with no grading option
1.257     albertel 1999:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2000: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2001: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
                   2002: 	    .$counter.'\');" TARGET=_self> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 2003: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 2004: 	if (($env{'form.command'} eq 'submission') || 
                   2005: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2006: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2007: 	}
1.180     albertel 2008: 	$request->print($toGrade);
1.41      ng       2009: 	return;
1.180     albertel 2010:     } else {
                   2011: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       2012:     }
1.33      ng       2013: 
1.121     ng       2014:     # essay grading message center
1.257     albertel 2015:     if ($env{'form.handgrade'} eq 'yes') {
                   2016: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2017: 	my $msgfor = $givenn.' '.$lastname;
                   2018: 	if (scalar(@col_fullnames) > 0) {
                   2019: 	    my $lastone = pop @col_fullnames;
                   2020: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   2021: 	}
                   2022: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       2023: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2024: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2025: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.118     ng       2026: 	    ',\''.$msgfor.'\')"; TARGET=_self>'.
1.350     albertel 2027: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
                   2028: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2029: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2030: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2031: 	    '<br />&nbsp;('.
                   2032: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       2033: 	$request->print($result);
1.118     ng       2034:     }
1.300     albertel 2035:     if ($perm{'vgr'}) {
1.297     www      2036: 	$request->print('<br />'.
1.300     albertel 2037: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2038: 						   $uname,$udom,'check'));
1.297     www      2039:     }
1.300     albertel 2040:     if ($perm{'opa'}) {
1.297     www      2041: 	$request->print('<br />'.
1.300     albertel 2042: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2043: 					 $uname,$udom,$symb,'check'));
1.297     www      2044:     }
1.41      ng       2045: 
                   2046:     my %seen = ();
                   2047:     my @partlist;
1.129     ng       2048:     my @gradePartRespid;
1.375     albertel 2049:     my @part_response_id = &flatten_responseType($responseType);
                   2050:     foreach my $part_response_id (@part_response_id) {
                   2051:     	my ($partid,$respid) = @{ $part_response_id };
                   2052: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2053: 	next if ($seen{$partid} > 0);
1.41      ng       2054: 	$seen{$partid}++;
1.393     albertel 2055: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2056: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2057: 	push @partlist,$partid;
1.129     ng       2058: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2059: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2060:     }
1.45      ng       2061:     $result='<input type="hidden" name="partlist'.$counter.
                   2062: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2063:     $result.='<input type="hidden" name="gradePartRespid'.
                   2064: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2065:     my $ctr = 0;
                   2066:     while ($ctr < scalar(@partlist)) {
                   2067: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2068: 	    $partlist[$ctr].'" />'."\n";
                   2069: 	$ctr++;
                   2070:     }
                   2071:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       2072: 
                   2073:     # print end of form
                   2074:     if ($counter == $total) {
1.297     www      2075: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2076: 	$endform.='<input type="button" value="Save & Next" '.
                   2077: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
                   2078: 	    $total.','.scalar(@partlist).');" TARGET=_self> &nbsp;'."\n";
                   2079: 	my $ntstu ='<select name="NTSTU">'.
                   2080: 	    '<option>1</option><option>2</option>'.
                   2081: 	    '<option>3</option><option>5</option>'.
                   2082: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2083: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2084: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.119     ng       2085: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2086: 	$endform.='<input type="button" value="Previous" '.
                   2087: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" TARGET=_self> &nbsp;'."\n".
                   2088: 	    '<input type="button" value="Next" '.
                   2089: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" TARGET=_self> &nbsp;';
                   2090: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2091:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2092:             "' name='increment' />";
1.45      ng       2093: 	$endform.='</td><tr></table></form>';
1.324     albertel 2094: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2095: 	$request->print($endform);
                   2096:     }
                   2097:     return '';
1.38      ng       2098: }
                   2099: 
1.44      ng       2100: #--- Retrieve the last submission for all the parts
1.38      ng       2101: sub get_last_submission {
1.119     ng       2102:     my ($returnhash)=@_;
1.46      ng       2103:     my (@string,$timestamp);
1.119     ng       2104:     if ($$returnhash{'version'}) {
1.46      ng       2105: 	my %lasthash=();
                   2106: 	my ($version);
1.119     ng       2107: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2108: 	    foreach my $key (sort(split(/\:/,
                   2109: 					$$returnhash{$version.':keys'}))) {
                   2110: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2111: 		$timestamp = 
                   2112: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2113: 	    }
                   2114: 	}
1.397     albertel 2115: 	foreach my $key (keys(%lasthash)) {
                   2116: 	    next if ($key !~ /\.submission$/);
                   2117: 
                   2118: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2119: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2120: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2121: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2122: 	}
                   2123:     }
1.397     albertel 2124:     if (!@string) {
                   2125: 	$string[0] =
1.398     albertel 2126: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2127:     }
                   2128:     return (\@string,\$timestamp);
1.38      ng       2129: }
1.35      ng       2130: 
1.44      ng       2131: #--- High light keywords, with style choosen by user.
1.38      ng       2132: sub keywords_highlight {
1.44      ng       2133:     my $string    = shift;
1.257     albertel 2134:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2135:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2136:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2137:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2138:     foreach my $keyword (@keylist) {
                   2139: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2140:     }
                   2141:     return $string;
1.38      ng       2142: }
1.36      ng       2143: 
1.44      ng       2144: #--- Called from submission routine
1.38      ng       2145: sub processHandGrade {
1.41      ng       2146:     my ($request) = shift;
1.324     albertel 2147:     my $symb   = &get_symb($request);
                   2148:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2149:     my $button = $env{'form.gradeOpt'};
                   2150:     my $ngrade = $env{'form.NCT'};
                   2151:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2152:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2153:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2154: 
1.44      ng       2155:     if ($button eq 'Save & Next') {
                   2156: 	my $ctr = 0;
                   2157: 	while ($ctr < $ngrade) {
1.257     albertel 2158: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2159: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2160: 	    if ($errorflag eq 'no_score') {
                   2161: 		$ctr++;
                   2162: 		next;
                   2163: 	    }
1.104     albertel 2164: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2165: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2166: 		$ctr++;
                   2167: 		next;
                   2168: 	    }
1.257     albertel 2169: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2170: 	    my ($subject,$message,$msgstatus) = ('','','');
1.386     raeburn  2171:             my $restitle = &Apache::lonnet::gettitle($symb);
                   2172:             my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2173:                                                 $symb,$udom,$uname);
                   2174:             my ($feedurl,$baseurl,$showsymb,$messagetail);
                   2175:             $feedurl = &Apache::lonnet::clutter($url);
                   2176:             if ($encrypturl =~ /^yes$/i) {
                   2177:                 $baseurl = &Apache::lonenc::encrypted($feedurl,1);
                   2178:                 $showsymb = &Apache::lonenc::encrypted($symb,1);
1.387     raeburn  2179:             } else {
                   2180:                 $baseurl = $feedurl;
                   2181:                 $showsymb = $symb;
1.386     raeburn  2182:             }
1.62      albertel 2183: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2184: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2185: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2186: 		$subject.=' ['.$restitle.']';
1.44      ng       2187: 		my (@msgnum) = split(/,/,$includemsg);
                   2188: 		foreach (@msgnum) {
1.257     albertel 2189: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2190: 		}
1.80      ng       2191: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2192: 		if ($env{'form.withgrades'.$ctr}) {
                   2193: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2194: 		    $messagetail = " for <a href=\"".
                   2195: 		                   $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
                   2196: 		}
                   2197: 		$msgstatus = 
                   2198:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2199: 						     $message.$messagetail,
                   2200:                                                      undef,$baseurl,undef,
                   2201:                                                      undef,undef,$showsymb,
                   2202:                                                      $restitle);
                   2203: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2204: 				$msgstatus);
1.44      ng       2205: 	    }
1.257     albertel 2206: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2207: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2208: 		foreach my $collabstr (@collabstrs) {
                   2209: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2210: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2211: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2212: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2213: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2214: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2215: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2216: 			    next;
                   2217: 			} else {
                   2218: 			    if ($message ne '') {
1.386     raeburn  2219:                                 $encrypturl=
                   2220:                                   &Apache::lonnet::EXT('resource.0.encrypturl',
                   2221:                                                        $symb,$udom,$collaborator);
                   2222:                                 if ($encrypturl =~ /^yes$/i) {
                   2223:                                     $baseurl = &Apache::lonenc::encrypted($feedurl,1);
                   2224:                                     $showsymb = &Apache::lonenc::encrypted($symb,1);
                   2225:                                 } else {
                   2226:                                     $baseurl = $feedurl;
                   2227:                                     $showsymb = $symb;
                   2228:                                 }
                   2229:                                 if ($env{'form.withgrades'.$ctr}) {
                   2230:                                     $messagetail = " for <a href=\"".
                   2231:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
                   2232: 
                   2233:                                 }
                   2234: 				$msgstatus = 
                   2235:                                     &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.150     albertel 2236: 			    }
1.104     albertel 2237: 			}
1.44      ng       2238: 		    }
                   2239: 		}
                   2240: 	    }
                   2241: 	    $ctr++;
                   2242: 	}
                   2243:     }
                   2244: 
1.257     albertel 2245:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2246: 	# Keywords sorted in alphabatical order
1.257     albertel 2247: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2248: 	my %keyhash = ();
1.257     albertel 2249: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2250: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2251: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2252: 	$env{'form.keywords'} = join(' ',@keywords);
                   2253: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2254: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2255: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2256: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2257: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2258: 
                   2259: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2260: 	# New messages are saved in env for the next student.
1.119     ng       2261: 	# All messages are saved in nohist_handgrade.db
                   2262: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2263: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2264: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2265: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2266: 		$idx++;
                   2267: 	    }
                   2268: 	    $ctr++;
1.41      ng       2269: 	}
1.119     ng       2270: 	$ctr = 0;
                   2271: 	while ($ctr < $ngrade) {
1.257     albertel 2272: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2273: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2274: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2275: 		$idx++;
                   2276: 	    }
                   2277: 	    $ctr++;
1.41      ng       2278: 	}
1.257     albertel 2279: 	$env{'form.savemsgN'} = --$idx;
                   2280: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2281: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2282: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2283:     }
1.44      ng       2284:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2285:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2286:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2287: 	my ($ctr,$total) = (0,0);
                   2288: 	while ($ctr < $ngrade) {
1.257     albertel 2289: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2290: 	    $ctr++;
                   2291: 	}
1.257     albertel 2292: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2293: 	$ctr = 0;
                   2294: 	while ($ctr < $total) {
1.257     albertel 2295: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2296: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2297: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2298: 	    &submission($request,$ctr,$total-1);
1.41      ng       2299: 	    $ctr++;
                   2300: 	}
                   2301: 	return '';
                   2302:     }
1.36      ng       2303: 
1.121     ng       2304: # Go directly to grade student - from submission or link from chart page
1.120     ng       2305:     if ($button eq 'Grade Student') {
1.324     albertel 2306: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2307: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2308: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2309: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2310: 	&submission($request,0,0);
                   2311: 	return '';
                   2312:     }
                   2313: 
1.44      ng       2314:     # Get the next/previous one or group of students
1.257     albertel 2315:     my $firststu = $env{'form.unamedom0'};
                   2316:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2317:     my $ctr = 2;
1.41      ng       2318:     while ($laststu eq '') {
1.257     albertel 2319: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2320: 	$ctr++;
                   2321: 	$laststu = $firststu if ($ctr > $ngrade);
                   2322:     }
1.44      ng       2323: 
1.41      ng       2324:     my (@parsedlist,@nextlist);
                   2325:     my ($nextflg) = 0;
1.294     albertel 2326:     foreach (sort 
                   2327: 	     {
                   2328: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2329: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2330: 		 }
                   2331: 		 return $a cmp $b;
                   2332: 	     } (keys(%$fullname))) {
1.41      ng       2333: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2334: 	    push @parsedlist,$_;
                   2335: 	}
                   2336: 	$nextflg = 1 if ($_ eq $laststu);
                   2337: 	if ($button eq 'Previous') {
                   2338: 	    last if ($_ eq $firststu);
                   2339: 	    push @parsedlist,$_;
                   2340: 	}
                   2341:     }
                   2342:     $ctr = 0;
                   2343:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2344:     my ($partlist) = &response_type($symb);
1.41      ng       2345:     foreach my $student (@parsedlist) {
1.257     albertel 2346: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2347: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2348: 	
                   2349: 	if ($submitonly eq 'queued') {
                   2350: 	    my %queue_status = 
                   2351: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2352: 							$udom,$uname);
                   2353: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2354: 	}
                   2355: 
1.156     albertel 2356: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2357: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2358: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2359: 	    my $submitted = 0;
1.248     albertel 2360: 	    my $ungraded = 0;
                   2361: 	    my $incorrect = 0;
1.145     albertel 2362: 	    foreach (keys(%status)) {
                   2363: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2364: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2365: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2366: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2367: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2368: 		    $submitted = 0;
                   2369: 		}
1.41      ng       2370: 	    }
1.156     albertel 2371: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2372: 				     $submitonly eq 'incorrect' ||
                   2373: 				     $submitonly eq 'graded'));
1.248     albertel 2374: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2375: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2376: 	}
                   2377: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2378: 	last if ($ctr == $ntstu);
1.41      ng       2379: 	$ctr++;
                   2380:     }
1.36      ng       2381: 
1.41      ng       2382:     $ctr = 0;
                   2383:     my $total = scalar(@nextlist)-1;
1.39      ng       2384: 
1.41      ng       2385:     foreach (sort @nextlist) {
                   2386: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2387: 	$env{'form.student'}  = $uname;
                   2388: 	$env{'form.userdom'}  = $udom;
                   2389: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2390: 	&submission($request,$ctr,$total);
                   2391: 	$ctr++;
                   2392:     }
                   2393:     if ($total < 0) {
1.398     albertel 2394: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
1.41      ng       2395: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2396: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2397: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2398: 	$request->print($the_end);
                   2399:     }
                   2400:     return '';
1.38      ng       2401: }
1.36      ng       2402: 
1.44      ng       2403: #---- Save the score and award for each student, if changed
1.38      ng       2404: sub saveHandGrade {
1.324     albertel 2405:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2406:     my @version_parts;
1.104     albertel 2407:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2408: 					   $env{'request.course.id'});
1.104     albertel 2409:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2410:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2411:     my @parts_graded;
1.77      ng       2412:     my %newrecord  = ();
                   2413:     my ($pts,$wgt) = ('','');
1.269     raeburn  2414:     my %aggregate = ();
                   2415:     my $aggregateflag = 0;
1.301     albertel 2416:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2417:     foreach my $new_part (@parts) {
1.337     banghart 2418: 	#collaborator ($submi may vary for different parts
1.259     banghart 2419: 	if ($submitter && $new_part ne $part) { next; }
                   2420: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2421: 	if ($dropMenu eq 'excused') {
1.259     banghart 2422: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2423: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2424: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2425: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2426: 		}
1.364     banghart 2427: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2428: 	    }
1.125     ng       2429: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2430: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2431: 	    foreach my $key (keys (%record)) {
1.259     banghart 2432: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2433: 	    }
1.259     banghart 2434: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2435: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2436:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2437: 
                   2438:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2439: 					       [$new_part]);
                   2440:             my $aggtries =$totaltries;
1.269     raeburn  2441:             if ($last_resets{$new_part}) {
1.270     albertel 2442:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2443: 					   $new_part);
1.269     raeburn  2444:             }
1.270     albertel 2445: 
                   2446:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2447:             if ($aggtries > 0) {
1.327     albertel 2448:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2449:                 $aggregateflag = 1;
                   2450:             }
1.125     ng       2451: 	} elsif ($dropMenu eq '') {
1.259     banghart 2452: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2453: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2454: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2455: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2456: 		next;
                   2457: 	    }
1.259     banghart 2458: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2459: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2460: 	    my $partial= $pts/$wgt;
1.259     banghart 2461: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2462: 		#do not update score for part if not changed.
1.346     banghart 2463:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2464: 		next;
1.251     banghart 2465: 	    } else {
1.259     banghart 2466: 	        push @parts_graded, $new_part;
1.153     albertel 2467: 	    }
1.259     banghart 2468: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2469: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2470: 	    }
1.259     banghart 2471: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2472: 	    if ($partial == 0) {
1.153     albertel 2473: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2474: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2475: 		}
1.41      ng       2476: 	    } else {
1.153     albertel 2477: 		if ($record{$reckey} ne 'correct_by_override') {
                   2478: 		    $newrecord{$reckey} = 'correct_by_override';
                   2479: 		}
                   2480: 	    }	    
                   2481: 	    if ($submitter && 
1.259     banghart 2482: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2483: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2484: 	    }
1.259     banghart 2485: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2486: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2487: 	}
1.259     banghart 2488: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2489: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2490: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2491: 	        $dropMenu eq 'reset status')
                   2492: 	   {
1.342     banghart 2493: 	    push (@version_parts,$new_part);
1.259     banghart 2494: 	}
1.41      ng       2495:     }
1.301     albertel 2496:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2497:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2498: 
1.344     albertel 2499:     if (%newrecord) {
                   2500:         if (@version_parts) {
1.364     banghart 2501:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2502:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2503: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2504: 	    foreach my $new_part (@version_parts) {
                   2505: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2506: 				$new_part,\%newrecord);
                   2507: 	    }
1.259     banghart 2508:         }
1.44      ng       2509: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2510: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2511: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2512: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2513:     }
1.269     raeburn  2514:     if ($aggregateflag) {
                   2515:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2516: 			      $cdom,$cnum);
1.269     raeburn  2517:     }
1.301     albertel 2518:     return ('',$pts,$wgt);
1.36      ng       2519: }
1.322     albertel 2520: 
1.380     albertel 2521: sub check_and_remove_from_queue {
                   2522:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2523:     my @ungraded_parts;
                   2524:     foreach my $part (@{$parts}) {
                   2525: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2526: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2527: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2528: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2529: 		) {
                   2530: 	    push(@ungraded_parts, $part);
                   2531: 	}
                   2532:     }
                   2533:     if ( !@ungraded_parts ) {
                   2534: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2535: 					       $cnum,$domain,$stuname);
                   2536:     }
                   2537: }
                   2538: 
1.337     banghart 2539: sub handback_files {
                   2540:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2541:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2542:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2543: 
                   2544:     my @part_response_id = &flatten_responseType($responseType);
                   2545:     foreach my $part_response_id (@part_response_id) {
                   2546:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2547: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2548:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2549:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2550:                 my $file_counter = 1;
1.367     albertel 2551: 		my $file_msg;
1.337     banghart 2552:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2553:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2554:                     my ($directory,$answer_file) = 
                   2555:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2556:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2557: 		        &file_name_version_ext($answer_file);
1.355     banghart 2558: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2559: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2560: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2561:                     # fix file name
                   2562:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2563:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2564:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2565:             	                                $save_file_name);
1.337     banghart 2566:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2567:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2568:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2569:                     } else {
1.360     banghart 2570:                         # mark the file as read only
                   2571:                         my @files = ($save_file_name);
1.372     albertel 2572:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2573:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2574: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2575: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2576: 			}
                   2577:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2578: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2579: 
1.337     banghart 2580:                     }
                   2581:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2582:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2583:                     $file_counter++;
                   2584:                 }
1.367     albertel 2585: 		my $subject = "File Handed Back by Instructor ";
                   2586: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2587: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2588: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2589: 		$message .= " and can be found in your portfolio space.";
                   2590: 		my $url = (&Apache::lonnet::decode_symb($symb))[2];
1.388     raeburn  2591: 		my $feedurl = &Apache::lonnet::clutter($url);
1.386     raeburn  2592:                 my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2593:                                                     $symb,$domain,$stuname);
                   2594:                 my ($baseurl,$showsymb);
                   2595:                 if ($encrypturl =~ /^yes$/i) {
                   2596:                     $baseurl = &Apache::lonenc::encrypted($feedurl,1);
                   2597:                     $showsymb = &Apache::lonenc::encrypted($symb,1);
                   2598:                 } else {
                   2599:                     $baseurl = $feedurl;
                   2600:                     $showsymb = $symb;
                   2601:                 }
                   2602:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2603: 		my $msgstatus = 
                   2604:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2605: 			 ' (File Returned) ['.$restitle.']',$message,undef,
                   2606:                          $baseurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2607:             }
                   2608:         }
1.338     banghart 2609:     return;
1.337     banghart 2610: }
                   2611: 
1.313     banghart 2612: sub get_submitted_files {
                   2613:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2614:     my @files;
                   2615:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2616:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2617:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2618:     	    push(@files,$file_url.$file);
                   2619:         }
                   2620:     }
                   2621:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2622:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2623:     }
                   2624:     return (\@files);
                   2625: }
1.322     albertel 2626: 
1.269     raeburn  2627: # ----------- Provides number of tries since last reset.
                   2628: sub get_num_tries {
                   2629:     my ($record,$last_reset,$part) = @_;
                   2630:     my $timestamp = '';
                   2631:     my $num_tries = 0;
                   2632:     if ($$record{'version'}) {
                   2633:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2634:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2635:                 $timestamp = $$record{$version.':timestamp'};
                   2636:                 if ($timestamp > $last_reset) {
                   2637:                     $num_tries ++;
                   2638:                 } else {
                   2639:                     last;
                   2640:                 }
                   2641:             }
                   2642:         }
                   2643:     }
                   2644:     return $num_tries;
                   2645: }
                   2646: 
                   2647: # ----------- Determine decrements required in aggregate totals 
                   2648: sub decrement_aggs {
                   2649:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2650:     my %decrement = (
                   2651:                         attempts => 0,
                   2652:                         users => 0,
                   2653:                         correct => 0
                   2654:                     );
                   2655:     $decrement{'attempts'} = $aggtries;
                   2656:     if ($solvedstatus =~ /^correct/) {
                   2657:         $decrement{'correct'} = 1;
                   2658:     }
                   2659:     if ($aggtries == $totaltries) {
                   2660:         $decrement{'users'} = 1;
                   2661:     }
                   2662:     foreach my $type (keys (%decrement)) {
                   2663:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2664:     }
                   2665:     return;
                   2666: }
                   2667: 
                   2668: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2669: sub get_last_resets {
1.270     albertel 2670:     my ($symb,$courseid,$partids) =@_;
                   2671:     my %last_resets;
1.269     raeburn  2672:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2673:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2674:     my @keys;
                   2675:     foreach my $part (@{$partids}) {
                   2676: 	push(@keys,"$symb\0$part\0resettime");
                   2677:     }
                   2678:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2679: 				     $cdom,$cname);
                   2680:     foreach my $part (@{$partids}) {
                   2681: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2682:     }
1.270     albertel 2683:     return %last_resets;
1.269     raeburn  2684: }
                   2685: 
1.251     banghart 2686: # ----------- Handles creating versions for portfolio files as answers
                   2687: sub version_portfiles {
1.343     banghart 2688:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2689:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2690:     my @returned_keys;
1.255     banghart 2691:     my $parts = join('|', @$parts_graded);
1.359     www      2692:     my $portfolio_root = &propath($domain,$stu_name).
                   2693: 	'/userfiles/portfolio';
1.277     albertel 2694:     foreach my $key (keys(%$record)) {
1.259     banghart 2695:         my $new_portfiles;
1.263     banghart 2696:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2697:             my @versioned_portfiles;
1.367     albertel 2698:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2699:             foreach my $file (@portfiles) {
1.306     banghart 2700:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2701:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2702: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2703: 		    &file_name_version_ext($answer_file);
1.306     banghart 2704:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2705:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2706:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2707:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2708:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2709:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2710:                         [$directory.$new_answer],
1.306     banghart 2711:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2712:                 }
1.252     banghart 2713:             }
1.343     banghart 2714:             $$record{$key} = join(',',@versioned_portfiles);
                   2715:             push(@returned_keys,$key);
1.251     banghart 2716:         }
                   2717:     } 
1.343     banghart 2718:     return (@returned_keys);   
1.305     banghart 2719: }
                   2720: 
1.307     banghart 2721: sub get_next_version {
1.341     banghart 2722:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2723:     my $version;
                   2724:     foreach my $row (@$dir_list) {
                   2725:         my ($file) = split(/\&/,$row,2);
                   2726:         my ($file_name,$file_version,$file_ext) =
                   2727: 	    &file_name_version_ext($file);
                   2728:         if (($file_name eq $answer_name) && 
                   2729: 	    ($file_ext eq $answer_ext)) {
                   2730:                 # gets here if filename and extension match, regardless of version
                   2731:                 if ($file_version ne '') {
                   2732:                 # a versioned file is found  so save it for later
                   2733:                 if ($file_version > $version) {
                   2734: 		    $version = $file_version;
                   2735: 	        }
                   2736:             }
                   2737:         }
                   2738:     } 
                   2739:     $version ++;
                   2740:     return($version);
                   2741: }
                   2742: 
1.305     banghart 2743: sub version_selected_portfile {
1.306     banghart 2744:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2745:     my ($answer_name,$answer_ver,$answer_ext) =
                   2746:         &file_name_version_ext($file_name);
                   2747:     my $new_answer;
                   2748:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2749:     if($env{'form.copy'} eq '-1') {
                   2750:         &Apache::lonnet::logthis('problem getting file '.$file_name);
                   2751:         $new_answer = 'problem getting file';
                   2752:     } else {
                   2753:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2754:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2755:                             $stu_name,$domain,'copy',
                   2756: 		        '/portfolio'.$directory.$new_answer);
                   2757:     }    
                   2758:     return ($new_answer);
1.251     banghart 2759: }
                   2760: 
1.304     albertel 2761: sub file_name_version_ext {
                   2762:     my ($file)=@_;
                   2763:     my @file_parts = split(/\./, $file);
                   2764:     my ($name,$version,$ext);
                   2765:     if (@file_parts > 1) {
                   2766: 	$ext=pop(@file_parts);
                   2767: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2768: 	    $version=pop(@file_parts);
                   2769: 	}
                   2770: 	$name=join('.',@file_parts);
                   2771:     } else {
                   2772: 	$name=join('.',@file_parts);
                   2773:     }
                   2774:     return($name,$version,$ext);
                   2775: }
                   2776: 
1.44      ng       2777: #--------------------------------------------------------------------------------------
                   2778: #
                   2779: #-------------------------- Next few routines handles grading by section or whole class
                   2780: #
                   2781: #--- Javascript to handle grading by section or whole class
1.42      ng       2782: sub viewgrades_js {
                   2783:     my ($request) = shift;
                   2784: 
1.41      ng       2785:     $request->print(<<VIEWJAVASCRIPT);
                   2786: <script type="text/javascript" language="javascript">
1.45      ng       2787:    function writePoint(partid,weight,point) {
1.125     ng       2788: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2789: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2790: 	if (point == "textval") {
1.125     ng       2791: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2792: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2793: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2794: 		var resetbox = false;
                   2795: 		for (var i=0; i<radioButton.length; i++) {
                   2796: 		    if (radioButton[i].checked) {
                   2797: 			textbox.value = i;
                   2798: 			resetbox = true;
                   2799: 		    }
                   2800: 		}
                   2801: 		if (!resetbox) {
                   2802: 		    textbox.value = "";
                   2803: 		}
                   2804: 		return;
                   2805: 	    }
1.109     matthew  2806: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2807: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2808: 				   ") greater than the weight for the part. Accept?");
                   2809: 		if (resp == false) {
                   2810: 		    textbox.value = "";
                   2811: 		    return;
                   2812: 		}
                   2813: 	    }
1.42      ng       2814: 	    for (var i=0; i<radioButton.length; i++) {
                   2815: 		radioButton[i].checked=false;
1.109     matthew  2816: 		if (parseFloat(point) == i) {
1.42      ng       2817: 		    radioButton[i].checked=true;
                   2818: 		}
                   2819: 	    }
1.41      ng       2820: 
1.42      ng       2821: 	} else {
1.125     ng       2822: 	    textbox.value = parseFloat(point);
1.42      ng       2823: 	}
1.41      ng       2824: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2825: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2826: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2827: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2828: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2829: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2830: 	    if (saveval != "correct") {
                   2831: 		scorename.value = point;
1.43      ng       2832: 		if (selname[0].selected != true) {
                   2833: 		    selname[0].selected = true;
                   2834: 		}
1.42      ng       2835: 	    }
                   2836: 	}
1.125     ng       2837: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2838:     }
                   2839: 
                   2840:     function writeRadText(partid,weight) {
1.125     ng       2841: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2842: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2843:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2844: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2845: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2846: 	    for (var i=0; i<radioButton.length; i++) {
                   2847: 		radioButton[i].checked=false;
                   2848: 
                   2849: 	    }
                   2850: 	    textbox.value = "";
                   2851: 
                   2852: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2853: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2854: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2855: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2856: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2857: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2858: 		if ((saveval != "correct") || override) {
1.42      ng       2859: 		    scorename.value = "";
1.125     ng       2860: 		    if (selval[1].selected) {
                   2861: 			selname[1].selected = true;
                   2862: 		    } else {
                   2863: 			selname[2].selected = true;
                   2864: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   2865: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   2866: 		    }
1.42      ng       2867: 		}
                   2868: 	    }
1.43      ng       2869: 	} else {
                   2870: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2871: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2872: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2873: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2874: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2875: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2876: 		if ((saveval != "correct") || override) {
1.125     ng       2877: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       2878: 		    selname[0].selected = true;
                   2879: 		}
                   2880: 	    }
                   2881: 	}	    
1.42      ng       2882:     }
                   2883: 
                   2884:     function changeSelect(partid,user) {
1.125     ng       2885: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2886: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       2887: 	var point  = textbox.value;
1.125     ng       2888: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       2889: 
1.109     matthew  2890: 	if (isNaN(point) || parseFloat(point) < 0) {
                   2891: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       2892: 	    textbox.value = "";
                   2893: 	    return;
                   2894: 	}
1.109     matthew  2895: 	if (parseFloat(point) > parseFloat(weight)) {
                   2896: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2897: 			       ") greater than the weight of the part. Accept?");
                   2898: 	    if (resp == false) {
                   2899: 		textbox.value = "";
                   2900: 		return;
                   2901: 	    }
                   2902: 	}
1.42      ng       2903: 	selval[0].selected = true;
                   2904:     }
                   2905: 
                   2906:     function changeOneScore(partid,user) {
1.125     ng       2907: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2908: 	if (selval[1].selected || selval[2].selected) {
                   2909: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   2910: 	    if (selval[2].selected) {
                   2911: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   2912: 	    }
1.269     raeburn  2913:         }
1.42      ng       2914:     }
                   2915: 
                   2916:     function resetEntry(numpart) {
                   2917: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       2918: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   2919: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   2920: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   2921: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       2922: 	    for (var i=0; i<radioButton.length; i++) {
                   2923: 		radioButton[i].checked=false;
                   2924: 
                   2925: 	    }
                   2926: 	    textbox.value = "";
                   2927: 	    selval[0].selected = true;
                   2928: 
                   2929: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2930: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2931: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2932: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2933: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   2934: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   2935: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   2936: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2937: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2938: 		if (saveselval == "excused") {
1.43      ng       2939: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       2940: 		} else {
1.43      ng       2941: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       2942: 		}
                   2943: 	    }
1.41      ng       2944: 	}
1.42      ng       2945:     }
                   2946: 
1.41      ng       2947: </script>
                   2948: VIEWJAVASCRIPT
1.42      ng       2949: }
                   2950: 
1.44      ng       2951: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       2952: sub viewgrades {
                   2953:     my ($request) = shift;
                   2954:     &viewgrades_js($request);
1.41      ng       2955: 
1.324     albertel 2956:     my ($symb) = &get_symb($request);
1.168     albertel 2957:     #need to make sure we have the correct data for later EXT calls, 
                   2958:     #thus invalidate the cache
                   2959:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 2960:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   2961:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 2962:     &Apache::lonnet::clear_EXT_cache_status();
                   2963: 
1.398     albertel 2964:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   2965:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       2966: 
                   2967:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 2968:     $result.=&jscriptNform($symb);
1.41      ng       2969: 
1.44      ng       2970:     #beginning of class grading form
1.41      ng       2971:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.106     albertel 2972: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.38      ng       2973: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.257     albertel 2974: 	'<input type="hidden" name="section" value="'.$env{'form.section'}.'" />'."\n".
                   2975: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   2976: 	'<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
                   2977: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       2978: 
1.126     ng       2979:     my $sectionClass;
1.257     albertel 2980:     if ($env{'form.section'} eq 'all') {
1.126     ng       2981: 	$sectionClass='Class </h3>';
1.257     albertel 2982:     } elsif ($env{'form.section'} eq 'none') {
1.126     ng       2983: 	$sectionClass='Students in no Section </h3>';
1.52      albertel 2984:     } else {
1.257     albertel 2985: 	$sectionClass='Students in Section '.$env{'form.section'}.'</h3>';
1.52      albertel 2986:     }
1.126     ng       2987:     $result.='<h3>Assign Common Grade To '.$sectionClass;
1.52      albertel 2988:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   2989: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       2990:     #radio buttons/text box for assigning points for a section or class.
                   2991:     #handles different parts of a problem
1.375     albertel 2992:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       2993:     my %weight = ();
                   2994:     my $ctsparts = 0;
1.41      ng       2995:     $result.='<table border="0">';
1.45      ng       2996:     my %seen = ();
1.375     albertel 2997:     my @part_response_id = &flatten_responseType($responseType);
                   2998:     foreach my $part_response_id (@part_response_id) {
                   2999:     	my ($partid,$respid) = @{ $part_response_id };
                   3000: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3001: 	next if $seen{$partid};
                   3002: 	$seen{$partid}++;
1.375     albertel 3003: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3004: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3005: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3006: 
1.44      ng       3007: 	$result.='<input type="hidden" name="partid_'.
                   3008: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3009: 	$result.='<input type="hidden" name="weight_'.
                   3010: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3011: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 3012: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3013: 	$result.='<table border="0"><tr>';  
1.41      ng       3014: 	my $ctr = 0;
1.42      ng       3015: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3016: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3017: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3018: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3019: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3020: 	    $ctr++;
                   3021: 	}
                   3022: 	$result.='</tr></table>';
1.44      ng       3023: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3024: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3025: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3026: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   3027: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3028: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3029: 		$weight{$partid}.')"> '.
1.401     albertel 3030: 	    '<option selected="selected"> </option>'.
1.125     ng       3031: 	    '<option>excused</option>'.
1.265     www      3032: 	    '<option>reset status</option></select></td>'.
1.266     albertel 3033:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       3034: 	$ctsparts++;
1.41      ng       3035:     }
1.52      albertel 3036:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   3037: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3038:     $result.='<input type="button" value="Revert to Default" '.
1.111     ng       3039: 	'onClick="javascript:resetEntry('.$ctsparts.');" TARGET=_self>';
1.41      ng       3040: 
1.44      ng       3041:     #table listing all the students in a section/class
                   3042:     #header of table
1.126     ng       3043:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       3044:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       3045: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       3046: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 3047:     my (@parts) = sort(&getpartlist($symb));
                   3048:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3049:     my @partids = ();
1.41      ng       3050:     foreach my $part (@parts) {
                   3051: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3052: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3053: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3054: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3055:         push(@partids, $partid);
1.324     albertel 3056: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3057: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 3058: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   3059: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       3060: 	    next;
1.207     albertel 3061: 	} else {
                   3062: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3063: 	}
1.53      albertel 3064: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 3065: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       3066:     }
                   3067:     $result.='</tr>';
1.44      ng       3068: 
1.270     albertel 3069:     my %last_resets = 
                   3070: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3071: 
1.41      ng       3072:     #get info for each student
1.44      ng       3073:     #list all the students - with points and grade status
1.257     albertel 3074:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3075:     my $ctr = 0;
1.294     albertel 3076:     foreach (sort 
                   3077: 	     {
                   3078: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3079: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3080: 		 }
                   3081: 		 return $a cmp $b;
                   3082: 	     } (keys(%$fullname))) {
1.126     ng       3083: 	$ctr++;
1.324     albertel 3084: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3085: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3086:     }
                   3087:     $result.='</table></td></tr></table>';
                   3088:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3089:     $result.='<input type="button" value="Save" '.
1.45      ng       3090: 	'onClick="javascript:submit();" TARGET=_self /></form>'."\n";
1.96      albertel 3091:     if (scalar(%$fullname) eq 0) {
                   3092: 	my $colspan=3+scalar(@parts);
1.398     albertel 3093: 	$result='<span class="LC_warning">There are no students in section "'.$env{'form.section'}.
                   3094: 	    '" with enrollment status "'.$env{'form.Status'}.'" to modify or grade.</span>';
1.96      albertel 3095:     }
1.324     albertel 3096:     $result.=&show_grading_menu_form($symb);
1.41      ng       3097:     return $result;
                   3098: }
                   3099: 
1.44      ng       3100: #--- call by previous routine to display each student
1.41      ng       3101: sub viewstudentgrade {
1.324     albertel 3102:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3103:     my ($uname,$udom) = split(/:/,$student);
                   3104:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3105:     my %aggregates = (); 
1.233     albertel 3106:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3107: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3108: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3109: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.112     ng       3110: 	'\')"; TARGET=_self>'.$fullname.'</a> '.
1.398     albertel 3111: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3112:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3113:     foreach my $apart (@$parts) {
                   3114: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3115: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3116:         $result.='<td align="center">';
1.269     raeburn  3117:         my ($aggtries,$totaltries);
                   3118:         unless (exists($aggregates{$part})) {
1.270     albertel 3119: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3120: 
                   3121: 	    $aggtries = $totaltries;
1.269     raeburn  3122:             if ($$last_resets{$part}) {  
1.270     albertel 3123:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3124: 					   $part);
                   3125:             }
1.269     raeburn  3126:             $result.='<input type="hidden" name="'.
                   3127:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3128:             $result.='<input type="hidden" name="'.
                   3129:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3130:             $aggregates{$part} = 1;
                   3131:         }
1.41      ng       3132: 	if ($type eq 'awarded') {
1.320     albertel 3133: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3134: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3135: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3136: 	    $result.='<input type="text" name="'.
1.89      albertel 3137: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3138: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3139: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3140: 	} elsif ($type eq 'solved') {
                   3141: 	    my ($status,$foo)=split(/_/,$score,2);
                   3142: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3143: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3144: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3145: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3146: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3147: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3148: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3149: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3150: 	    $result.='<option>reset status</option>';
1.126     ng       3151: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3152: 	} else {
                   3153: 	    $result.='<input type="hidden" name="'.
                   3154: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3155: 		    "\n";
1.233     albertel 3156: 	    $result.='<input type="text" name="'.
1.122     ng       3157: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3158: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3159: 	}
                   3160:     }
                   3161:     $result.='</tr>';
                   3162:     return $result;
1.38      ng       3163: }
                   3164: 
1.44      ng       3165: #--- change scores for all the students in a section/class
                   3166: #    record does not get update if unchanged
1.38      ng       3167: sub editgrades {
1.41      ng       3168:     my ($request) = @_;
                   3169: 
1.324     albertel 3170:     my $symb=&get_symb($request);
1.398     albertel 3171:     my $title='<h3><span class="LC_info">Current Grade Status</span></h3>';
                   3172:     $title.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4><br />'."\n";
                   3173:     $title.='<h4><b>Section: </b>'.$env{'form.section'}.'</h4>'."\n";
1.126     ng       3174: 
1.44      ng       3175:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3176:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3177: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3178: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3179: 
                   3180:     my %scoreptr = (
                   3181: 		    'correct'  =>'correct_by_override',
                   3182: 		    'incorrect'=>'incorrect_by_override',
                   3183: 		    'excused'  =>'excused',
                   3184: 		    'ungraded' =>'ungraded_attempted',
                   3185: 		    'nothing'  => '',
                   3186: 		    );
1.257     albertel 3187:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3188: 
1.44      ng       3189:     my (@partid);
                   3190:     my %weight = ();
1.54      albertel 3191:     my %columns = ();
1.44      ng       3192:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3193: 
1.324     albertel 3194:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3195:     my $header;
1.257     albertel 3196:     while ($ctr < $env{'form.totalparts'}) {
                   3197: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3198: 	push @partid,$partid;
1.257     albertel 3199: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3200: 	$ctr++;
1.54      albertel 3201:     }
1.324     albertel 3202:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3203:     foreach my $partid (@partid) {
                   3204: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3205: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3206: 	$columns{$partid}=2;
                   3207: 	foreach my $stores (@parts) {
                   3208: 	    my ($part,$type) = &split_part_type($stores);
                   3209: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3210: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3211: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3212: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3213: 	    $display =~ s/Number of Attempts/Tries/;
                   3214: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3215: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3216: 	    $columns{$partid}+=2;
                   3217: 	}
                   3218:     }
                   3219:     foreach my $partid (@partid) {
1.324     albertel 3220: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3221: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3222: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3223: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3224: 
1.44      ng       3225:     }
                   3226:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3227:     $result .= $header;
1.44      ng       3228:     $result .= '</tr>'."\n";
1.93      albertel 3229:     my $noupdate;
1.126     ng       3230:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3231:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3232: 	my $line;
1.257     albertel 3233: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3234: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3235: 	my %newrecord;
                   3236: 	my $updateflag = 0;
1.281     albertel 3237: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3238: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3239: 	if (!&canmodify($usec)) {
1.126     ng       3240: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3241: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3242: 	    next;
                   3243: 	}
1.269     raeburn  3244:         my %aggregate = ();
                   3245:         my $aggregateflag = 0;
1.281     albertel 3246: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3247: 	foreach (@partid) {
1.257     albertel 3248: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3249: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3250: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3251: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3252: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3253: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3254: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3255: 	    my $score;
                   3256: 	    if ($partial eq '') {
1.257     albertel 3257: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3258: 	    } elsif ($partial > 0) {
                   3259: 		$score = 'correct_by_override';
                   3260: 	    } elsif ($partial == 0) {
                   3261: 		$score = 'incorrect_by_override';
                   3262: 	    }
1.257     albertel 3263: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3264: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3265: 
1.292     albertel 3266: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3267: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3268: 	    if ($dropMenu eq 'reset status' &&
                   3269: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3270: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3271: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3272: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3273: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3274: 		$updateflag = 1;
1.269     raeburn  3275:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3276:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3277:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3278:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3279:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3280:                     $aggregateflag = 1;
                   3281:                 }
1.139     albertel 3282: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3283: 		$updateflag = 1;
                   3284: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3285: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3286: 		$rec_update++;
1.125     ng       3287: 	    }
                   3288: 
1.93      albertel 3289: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3290: 		'<td align="center">'.$awarded.
                   3291: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3292: 
1.54      albertel 3293: 
                   3294: 	    my $partid=$_;
                   3295: 	    foreach my $stores (@parts) {
                   3296: 		my ($part,$type) = &split_part_type($stores);
                   3297: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3298: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3299: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3300: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3301: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3302: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3303: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3304: 		    $updateflag=1;
                   3305: 		}
1.93      albertel 3306: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3307: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3308: 	    }
1.44      ng       3309: 	}
1.93      albertel 3310: 	$line.='</tr>'."\n";
1.301     albertel 3311: 
                   3312: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3313: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3314: 
1.44      ng       3315: 	if ($updateflag) {
                   3316: 	    $count++;
1.257     albertel 3317: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3318: 				    $udom,$uname);
1.301     albertel 3319: 
                   3320: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3321: 					      $cnum,$udom,$uname)) {
                   3322: 		# need to figure out if should be in queue.
                   3323: 		my %record =  
                   3324: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3325: 					     $udom,$uname);
                   3326: 		my $all_graded = 1;
                   3327: 		my $none_graded = 1;
                   3328: 		foreach my $part (@parts) {
                   3329: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3330: 			$all_graded = 0;
                   3331: 		    } else {
                   3332: 			$none_graded = 0;
                   3333: 		    }
                   3334: 		}
                   3335: 
                   3336: 		if ($all_graded || $none_graded) {
                   3337: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3338: 							   $symb,$cdom,$cnum,
                   3339: 							   $udom,$uname);
                   3340: 		}
                   3341: 	    }
                   3342: 
1.126     ng       3343: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3344: 	    $updateCtr++;
1.93      albertel 3345: 	} else {
1.126     ng       3346: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3347: 	    $noupdateCtr++;
1.44      ng       3348: 	}
1.269     raeburn  3349:         if ($aggregateflag) {
                   3350:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3351: 				  $cdom,$cnum);
1.269     raeburn  3352:         }
1.93      albertel 3353:     }
                   3354:     if ($noupdate) {
1.126     ng       3355: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3356: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3357: 	$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       3358:     }
1.72      ng       3359:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3360: 	&show_grading_menu_form ($symb);
1.125     ng       3361:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3362: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3363: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3364:     return $title.$msg.$result;
1.5       albertel 3365: }
1.54      albertel 3366: 
                   3367: sub split_part_type {
                   3368:     my ($partstr) = @_;
                   3369:     my ($temp,@allparts)=split(/_/,$partstr);
                   3370:     my $type=pop(@allparts);
                   3371:     my $part=join('.',@allparts);
                   3372:     return ($part,$type);
                   3373: }
                   3374: 
1.44      ng       3375: #------------- end of section for handling grading by section/class ---------
                   3376: #
                   3377: #----------------------------------------------------------------------------
                   3378: 
1.5       albertel 3379: 
1.44      ng       3380: #----------------------------------------------------------------------------
                   3381: #
                   3382: #-------------------------- Next few routines handles grading by csv upload
                   3383: #
                   3384: #--- Javascript to handle csv upload
1.27      albertel 3385: sub csvupload_javascript_reverse_associate {
1.246     albertel 3386:     my $error1=&mt('You need to specify the username or ID');
                   3387:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3388:   return(<<ENDPICK);
                   3389:   function verify(vf) {
                   3390:     var foundsomething=0;
                   3391:     var founduname=0;
1.243     albertel 3392:     var foundID=0;
1.27      albertel 3393:     for (i=0;i<=vf.nfields.value;i++) {
                   3394:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3395:       if (i==0 && tw!=0) { foundID=1; }
                   3396:       if (i==1 && tw!=0) { founduname=1; }
                   3397:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3398:     }
1.246     albertel 3399:     if (founduname==0 && foundID==0) {
                   3400: 	alert('$error1');
                   3401: 	return;
1.27      albertel 3402:     }
                   3403:     if (foundsomething==0) {
1.246     albertel 3404: 	alert('$error2');
                   3405: 	return;
1.27      albertel 3406:     }
                   3407:     vf.submit();
                   3408:   }
                   3409:   function flip(vf,tf) {
                   3410:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3411:     var i;
                   3412:     for (i=0;i<=vf.nfields.value;i++) {
                   3413:       //can not pick the same destination field for both name and domain
                   3414:       if (((i ==0)||(i ==1)) && 
                   3415:           ((tf==0)||(tf==1)) && 
                   3416:           (i!=tf) &&
                   3417:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3418:         eval('vf.f'+i+'.selectedIndex=0;')
                   3419:       }
                   3420:     }
                   3421:   }
                   3422: ENDPICK
                   3423: }
                   3424: 
                   3425: sub csvupload_javascript_forward_associate {
1.246     albertel 3426:     my $error1=&mt('You need to specify the username or ID');
                   3427:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3428:   return(<<ENDPICK);
                   3429:   function verify(vf) {
                   3430:     var foundsomething=0;
                   3431:     var founduname=0;
1.243     albertel 3432:     var foundID=0;
1.27      albertel 3433:     for (i=0;i<=vf.nfields.value;i++) {
                   3434:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3435:       if (tw==1) { foundID=1; }
                   3436:       if (tw==2) { founduname=1; }
                   3437:       if (tw>3) { foundsomething=1; }
1.27      albertel 3438:     }
1.246     albertel 3439:     if (founduname==0 && foundID==0) {
                   3440: 	alert('$error1');
                   3441: 	return;
1.27      albertel 3442:     }
                   3443:     if (foundsomething==0) {
1.246     albertel 3444: 	alert('$error2');
                   3445: 	return;
1.27      albertel 3446:     }
                   3447:     vf.submit();
                   3448:   }
                   3449:   function flip(vf,tf) {
                   3450:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3451:     var i;
                   3452:     //can not pick the same destination field twice
                   3453:     for (i=0;i<=vf.nfields.value;i++) {
                   3454:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3455:         eval('vf.f'+i+'.selectedIndex=0;')
                   3456:       }
                   3457:     }
                   3458:   }
                   3459: ENDPICK
                   3460: }
                   3461: 
1.26      albertel 3462: sub csvuploadmap_header {
1.324     albertel 3463:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3464:     my $javascript;
1.257     albertel 3465:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3466: 	$javascript=&csvupload_javascript_reverse_associate();
                   3467:     } else {
                   3468: 	$javascript=&csvupload_javascript_forward_associate();
                   3469:     }
1.45      ng       3470: 
1.324     albertel 3471:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3472:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3473:     my $ignore=&mt('Ignore First Line');
1.41      ng       3474:     $request->print(<<ENDPICK);
1.26      albertel 3475: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3476: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3477: $result
1.326     albertel 3478: <hr />
1.26      albertel 3479: <h3>Identify fields</h3>
                   3480: Total number of records found in file: $distotal <hr />
                   3481: Enter as many fields as you can. The system will inform you and bring you back
                   3482: to this page if the data selected is insufficient to run your class.<hr />
                   3483: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3484: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3485: <input type="hidden" name="associate"  value="" />
                   3486: <input type="hidden" name="phase"      value="three" />
                   3487: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3488: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3489: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3490: <input type="hidden" name="upfile_associate" 
1.257     albertel 3491:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3492: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3493: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3494: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3495: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3496: <hr />
                   3497: <script type="text/javascript" language="Javascript">
                   3498: $javascript
                   3499: </script>
                   3500: ENDPICK
1.118     ng       3501:     return '';
1.26      albertel 3502: 
                   3503: }
                   3504: 
                   3505: sub csvupload_fields {
1.324     albertel 3506:     my ($symb) = @_;
                   3507:     my (@parts) = &getpartlist($symb);
1.243     albertel 3508:     my @fields=(['ID','Student ID'],
                   3509: 		['username','Student Username'],
                   3510: 		['domain','Student Domain']);
1.324     albertel 3511:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3512:     foreach my $part (sort(@parts)) {
                   3513: 	my @datum;
                   3514: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3515: 	my $name=$part;
                   3516: 	if  (!$display) { $display = $name; }
                   3517: 	@datum=($name,$display);
1.244     albertel 3518: 	if ($name=~/^stores_(.*)_awarded/) {
                   3519: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3520: 	}
1.41      ng       3521: 	push(@fields,\@datum);
                   3522:     }
                   3523:     return (@fields);
1.26      albertel 3524: }
                   3525: 
                   3526: sub csvuploadmap_footer {
1.41      ng       3527:     my ($request,$i,$keyfields) =@_;
                   3528:     $request->print(<<ENDPICK);
1.26      albertel 3529: </table>
                   3530: <input type="hidden" name="nfields" value="$i" />
                   3531: <input type="hidden" name="keyfields" value="$keyfields" />
                   3532: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3533: </form>
                   3534: ENDPICK
                   3535: }
                   3536: 
1.283     albertel 3537: sub checkforfile_js {
1.86      ng       3538:     my $result =<<CSVFORMJS;
                   3539: <script type="text/javascript" language="javascript">
                   3540:     function checkUpload(formname) {
                   3541: 	if (formname.upfile.value == "") {
                   3542: 	    alert("Please use the browse button to select a file from your local directory.");
                   3543: 	    return false;
                   3544: 	}
                   3545: 	formname.submit();
                   3546:     }
                   3547:     </script>
                   3548: CSVFORMJS
1.283     albertel 3549:     return $result;
                   3550: }
                   3551: 
                   3552: sub upcsvScores_form {
                   3553:     my ($request) = shift;
1.324     albertel 3554:     my ($symb)=&get_symb($request);
1.283     albertel 3555:     if (!$symb) {return '';}
                   3556:     my $result=&checkforfile_js();
1.257     albertel 3557:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3558:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3559:     $result.=$table;
1.326     albertel 3560:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3561:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3562:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3563: 	'.</b></td></tr>'."\n";
                   3564:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3565:     my $upload=&mt("Upload Scores");
1.86      ng       3566:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3567:     my $ignore=&mt('Ignore First Line');
1.86      ng       3568:     $result.=<<ENDUPFORM;
1.106     albertel 3569: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3570: <input type="hidden" name="symb" value="$symb" />
                   3571: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3572: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3573: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3574: $upfile_select
1.370     www      3575: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3576: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3577: </form>
                   3578: ENDUPFORM
1.370     www      3579:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3580:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3581:     .'</td></tr></table>'."\n";
1.86      ng       3582:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3583:     $result.=&show_grading_menu_form($symb);
1.86      ng       3584:     return $result;
                   3585: }
                   3586: 
                   3587: 
1.26      albertel 3588: sub csvuploadmap {
1.41      ng       3589:     my ($request)= @_;
1.324     albertel 3590:     my ($symb)=&get_symb($request);
1.41      ng       3591:     if (!$symb) {return '';}
1.72      ng       3592: 
1.41      ng       3593:     my $datatoken;
1.257     albertel 3594:     if (!$env{'form.datatoken'}) {
1.41      ng       3595: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3596:     } else {
1.257     albertel 3597: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3598: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3599:     }
1.41      ng       3600:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3601:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3602:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3603:     my ($i,$keyfields);
                   3604:     if (@records) {
1.324     albertel 3605: 	my @fields=&csvupload_fields($symb);
1.45      ng       3606: 
1.257     albertel 3607: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3608: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3609: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3610: 							  \@fields);
                   3611: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3612: 	    chop($keyfields);
                   3613: 	} else {
                   3614: 	    unshift(@fields,['none','']);
                   3615: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3616: 							    \@fields);
1.311     banghart 3617:             foreach my $rec (@records) {
                   3618:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3619:                 if (%temp) {
                   3620:                     $keyfields=join(',',sort(keys(%temp)));
                   3621:                     last;
                   3622:                 }
                   3623:             }
1.41      ng       3624: 	}
                   3625:     }
                   3626:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3627:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3628: 
1.41      ng       3629:     return '';
1.27      albertel 3630: }
                   3631: 
1.246     albertel 3632: sub csvuploadoptions {
1.41      ng       3633:     my ($request)= @_;
1.324     albertel 3634:     my ($symb)=&get_symb($request);
1.257     albertel 3635:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3636:     my $ignore=&mt('Ignore First Line');
                   3637:     $request->print(<<ENDPICK);
                   3638: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3639: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3640: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3641: <!--
1.246     albertel 3642: <p>
                   3643: <label>
                   3644:    <input type="checkbox" name="show_full_results" />
                   3645:    Show a table of all changes
                   3646: </label>
                   3647: </p>
1.302     albertel 3648: -->
1.246     albertel 3649: <p>
                   3650: <label>
                   3651:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3652:    Overwrite any existing score
                   3653: </label>
                   3654: </p>
                   3655: ENDPICK
                   3656:     my %fields=&get_fields();
                   3657:     if (!defined($fields{'domain'})) {
1.257     albertel 3658: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3659: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3660:     }
1.257     albertel 3661:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3662: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3663: 	my $cleankey=$1;
                   3664: 	if ($cleankey eq 'command') { next; }
                   3665: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3666: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3667:     }
                   3668:     # FIXME do a check for any duplicated user ids...
                   3669:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3670:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3671: <hr /></form>'."\n");
1.324     albertel 3672:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3673:     return '';
                   3674: }
                   3675: 
                   3676: sub get_fields {
                   3677:     my %fields;
1.257     albertel 3678:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3679:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3680: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3681: 	    if ($env{'form.f'.$i} ne 'none') {
                   3682: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3683: 	    }
                   3684: 	} else {
1.257     albertel 3685: 	    if ($env{'form.f'.$i} ne 'none') {
                   3686: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3687: 	    }
                   3688: 	}
1.27      albertel 3689:     }
1.246     albertel 3690:     return %fields;
                   3691: }
                   3692: 
                   3693: sub csvuploadassign {
                   3694:     my ($request)= @_;
1.324     albertel 3695:     my ($symb)=&get_symb($request);
1.246     albertel 3696:     if (!$symb) {return '';}
1.345     bowersj2 3697:     my $error_msg = '';
1.246     albertel 3698:     &Apache::loncommon::load_tmp_file($request);
                   3699:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3700:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3701:     my %fields=&get_fields();
1.41      ng       3702:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3703:     my $courseid=$env{'request.course.id'};
1.97      albertel 3704:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3705:     my @notallowed;
1.41      ng       3706:     my @skipped;
                   3707:     my $countdone=0;
                   3708:     foreach my $grade (@gradedata) {
                   3709: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3710: 	my $domain;
                   3711: 	if ($entries{$fields{'domain'}}) {
                   3712: 	    $domain=$entries{$fields{'domain'}};
                   3713: 	} else {
1.257     albertel 3714: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3715: 	}
1.243     albertel 3716: 	$domain=~s/\s//g;
1.41      ng       3717: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3718: 	$username=~s/\s//g;
1.243     albertel 3719: 	if (!$username) {
                   3720: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3721: 	    $id=~s/\s//g;
1.243     albertel 3722: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3723: 	    $username=$ids{$id};
                   3724: 	}
1.41      ng       3725: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3726: 	    my $id=$entries{$fields{'ID'}};
                   3727: 	    $id=~s/\s//g;
                   3728: 	    if ($id) {
                   3729: 		push(@skipped,"$id:$domain");
                   3730: 	    } else {
                   3731: 		push(@skipped,"$username:$domain");
                   3732: 	    }
1.41      ng       3733: 	    next;
                   3734: 	}
1.108     albertel 3735: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3736: 	if (!&canmodify($usec)) {
                   3737: 	    push(@notallowed,"$username:$domain");
                   3738: 	    next;
                   3739: 	}
1.244     albertel 3740: 	my %points;
1.41      ng       3741: 	my %grades;
                   3742: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3743: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3744: 		$dest eq 'domain') { next; }
                   3745: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3746: 	    if ($dest=~/stores_(.*)_points/) {
                   3747: 		my $part=$1;
                   3748: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3749: 					      $symb,$domain,$username);
1.345     bowersj2 3750:                 if ($wgt) {
                   3751:                     $entries{$fields{$dest}}=~s/\s//g;
                   3752:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3753:                     my $award='correct_by_override';
                   3754:                     $grades{"resource.$part.awarded"}=$pcr;
                   3755:                     $grades{"resource.$part.solved"}=$award;
                   3756:                     $points{$part}=1;
                   3757:                 } else {
                   3758:                     $error_msg = "<br />" .
                   3759:                         &mt("Some point values were assigned"
                   3760:                             ." for problems with a weight "
                   3761:                             ."of zero. These values were "
                   3762:                             ."ignored.");
                   3763:                 }
1.244     albertel 3764: 	    } else {
                   3765: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3766: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3767: 		my $store_key=$dest;
                   3768: 		$store_key=~s/^stores/resource/;
                   3769: 		$store_key=~s/_/\./g;
                   3770: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3771: 	    }
1.41      ng       3772: 	}
1.398     albertel 3773: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3774: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.244     albertel 3775: #	&Apache::lonnet::logthis(" storing ".(join('-',%grades)));
1.302     albertel 3776: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3777: 					   $env{'request.course.id'},
                   3778: 					   $domain,$username);
                   3779: 	if ($result eq 'ok') {
                   3780: 	    $request->print('.');
                   3781: 	} else {
                   3782: 	    $request->print("<p>
1.398     albertel 3783:                               <span class=\"LC_error\">
                   3784:                                  Failed to save student $username:$domain.
                   3785:                                  Message when trying to save was ($result)
                   3786:                               </span>
1.302     albertel 3787:                              </p>" );
                   3788: 	}
1.41      ng       3789: 	$request->rflush();
                   3790: 	$countdone++;
                   3791:     }
1.398     albertel 3792:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3793:     if (@skipped) {
1.398     albertel 3794: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3795: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3796:     }
                   3797:     if (@notallowed) {
1.398     albertel 3798: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3799: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3800:     }
1.106     albertel 3801:     $request->print("<br />\n");
1.324     albertel 3802:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3803:     return $error_msg;
1.26      albertel 3804: }
1.44      ng       3805: #------------- end of section for handling csv file upload ---------
                   3806: #
                   3807: #-------------------------------------------------------------------
                   3808: #
1.122     ng       3809: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3810: #
                   3811: #--- Select a page/sequence and a student to grade
1.68      ng       3812: sub pickStudentPage {
                   3813:     my ($request) = shift;
                   3814: 
                   3815:     $request->print(<<LISTJAVASCRIPT);
                   3816: <script type="text/javascript" language="javascript">
                   3817: 
                   3818: function checkPickOne(formname) {
1.76      ng       3819:     if (radioSelection(formname.student) == null) {
1.68      ng       3820: 	alert("Please select the student you wish to grade.");
                   3821: 	return;
                   3822:     }
1.125     ng       3823:     ptr = pullDownSelection(formname.selectpage);
                   3824:     formname.page.value = formname["page"+ptr].value;
                   3825:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3826:     formname.submit();
                   3827: }
                   3828: 
                   3829: </script>
                   3830: LISTJAVASCRIPT
1.118     ng       3831:     &commonJSfunctions($request);
1.324     albertel 3832:     my ($symb) = &get_symb($request);
1.257     albertel 3833:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3834:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3835:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3836: 
1.398     albertel 3837:     my $result='<h3><span class="LC_info">&nbsp;'.
                   3838: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       3839: 
1.80      ng       3840:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3841:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.74      albertel 3842:     my ($titles,$symbx) = &getSymbMap($request);
1.137     albertel 3843:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3844: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3845: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3846:     my $ctr=0;
1.68      ng       3847:     foreach (@$titles) {
                   3848: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3849: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 3850: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       3851: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3852: 	$ctr++;
1.68      ng       3853:     }
1.326     albertel 3854:     $result.= '</select>'."<br />\n";
1.70      ng       3855:     $ctr=0;
                   3856:     foreach (@$titles) {
                   3857: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3858: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3859: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3860: 	$ctr++;
                   3861:     }
1.72      ng       3862:     $result.='<input type="hidden" name="page" />'."\n".
                   3863: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3864: 
1.401     albertel 3865:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 3866: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       3867: 
1.71      ng       3868:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 3869: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 3870: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 3871: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.72      ng       3872: 
1.68      ng       3873:     $result.='<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
1.257     albertel 3874: 	'<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.72      ng       3875: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.80      ng       3876: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.257     albertel 3877: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       3878: 
1.382     albertel 3879:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   3880: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   3881: 
1.80      ng       3882:     $result.='&nbsp;<input type="button" '.
1.126     ng       3883: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       3884: 
1.68      ng       3885:     $request->print($result);
                   3886: 
1.326     albertel 3887:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       3888: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3889: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       3890: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3891: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       3892: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3893: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       3894:  
1.76      ng       3895:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       3896:     my $ptr = 1;
1.294     albertel 3897:     foreach my $student (sort 
                   3898: 			 {
                   3899: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3900: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3901: 			     }
                   3902: 			     return $a cmp $b;
                   3903: 			 } (keys(%$fullname))) {
1.68      ng       3904: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       3905: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   3906: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 3907: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   3908: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       3909: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       3910: 	$ptr++;
                   3911:     }
1.381     albertel 3912:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   3913:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       3914:     $studentTable.='<input type="button" '.
                   3915: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       3916: 
1.324     albertel 3917:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       3918:     $request->print($studentTable);
                   3919: 
                   3920:     return '';
                   3921: }
                   3922: 
                   3923: sub getSymbMap {
1.74      albertel 3924:     my ($request) = @_;
1.132     bowersj2 3925:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       3926: 
                   3927:     my %symbx = ();
                   3928:     my @titles = ();
1.117     bowersj2 3929:     my $minder = 0;
                   3930: 
                   3931:     # Gather every sequence that has problems.
1.240     albertel 3932:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   3933: 					       1,0,1);
1.117     bowersj2 3934:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 3935: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 3936: 	    my $title = $minder.'.'.
                   3937: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   3938: 	    push(@titles, $title); # minder in case two titles are identical
                   3939: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 3940: 	    $minder++;
1.241     albertel 3941: 	}
1.68      ng       3942:     }
                   3943:     return \@titles,\%symbx;
                   3944: }
                   3945: 
1.72      ng       3946: #
                   3947: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       3948: sub displayPage {
                   3949:     my ($request) = shift;
                   3950: 
1.324     albertel 3951:     my ($symb) = &get_symb($request);
1.257     albertel 3952:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3953:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3954:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3955:     my $pageTitle = $env{'form.page'};
1.103     albertel 3956:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 3957:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   3958:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 3959: 
                   3960:     #need to make sure we have the correct data for later EXT calls, 
                   3961:     #thus invalidate the cache
                   3962:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3963:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3964:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3965:     &Apache::lonnet::clear_EXT_cache_status();
                   3966: 
1.103     albertel 3967:     if (!&canview($usec)) {
1.398     albertel 3968: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 3969: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 3970: 	return;
                   3971:     }
1.398     albertel 3972:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 3973:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       3974: 	'</h3>'."\n";
1.382     albertel 3975:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   3976: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   3977:     } else {
                   3978: 	delete($env{'form.CODE'});
                   3979:     }
1.71      ng       3980:     &sub_page_js($request);
                   3981:     $request->print($result);
                   3982: 
1.132     bowersj2 3983:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 3984:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       3985:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 3986:     if (!$map) {
1.398     albertel 3987: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 3988: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 3989: 	return; 
                   3990:     }
1.68      ng       3991:     my $iterator = $navmap->getIterator($map->map_start(),
                   3992: 					$map->map_finish());
                   3993: 
1.71      ng       3994:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       3995: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 3996: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   3997: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       3998: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 3999: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.72      ng       4000: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.125     ng       4001: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4002: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4003: 
1.382     albertel 4004:     if (defined($env{'form.CODE'})) {
                   4005: 	$studentTable.=
                   4006: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4007:     }
1.381     albertel 4008:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4009: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4010: 	'/check.gif" height="16" border="0" />';
                   4011: 
1.118     ng       4012:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4013: 	' symbol.'."\n".
1.71      ng       4014: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4015: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4016: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4017: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4018: 
1.329     albertel 4019:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4020:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4021:     $iterator->next(); # skip the first BEGIN_MAP
                   4022:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4023:     while ($depth > 0) {
1.68      ng       4024:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4025:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4026: 
1.385     albertel 4027:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4028: 	    my $parts = $curRes->parts();
1.68      ng       4029:             my $title = $curRes->compTitle();
1.71      ng       4030: 	    my $symbx = $curRes->symb();
1.196     albertel 4031: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4032: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4033: 	    $studentTable.='<td valign="top">';
1.382     albertel 4034: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4035: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4036: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4037: 					     undef,'both',\%form);
1.71      ng       4038: 	    } else {
1.382     albertel 4039: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4040: 		$companswer =~ s|<form(.*?)>||g;
                   4041: 		$companswer =~ s|</form>||g;
1.71      ng       4042: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4043: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4044: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4045: #		}
1.116     ng       4046: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4047: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4048: 	    }
                   4049: 
1.257     albertel 4050: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4051: 
1.257     albertel 4052: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4053: 		if ($record{'version'} eq '') {
1.398     albertel 4054: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4055: 		} else {
1.116     ng       4056: 		    my %responseType = ();
                   4057: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4058: 			my @responseIds =$curRes->responseIds($partid);
                   4059: 			my @responseType =$curRes->responseType($partid);
                   4060: 			my %responseIds;
                   4061: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4062: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4063: 			}
                   4064: 			$responseType{$partid} = \%responseIds;
1.116     ng       4065: 		    }
1.148     albertel 4066: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4067: 
1.71      ng       4068: 		}
1.257     albertel 4069: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4070: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4071: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4072: 									$env{'request.course.id'},
1.71      ng       4073: 									'','.submission');
                   4074:  
                   4075: 	    }
1.103     albertel 4076: 	    if (&canmodify($usec)) {
                   4077: 		foreach my $partid (@{$parts}) {
                   4078: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4079: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4080: 		    $question++;
                   4081: 		}
1.196     albertel 4082: 		$prob++;
1.71      ng       4083: 	    }
                   4084: 	    $studentTable.='</td></tr>';
1.68      ng       4085: 
1.103     albertel 4086: 	}
1.68      ng       4087:         $curRes = $iterator->next();
                   4088:     }
                   4089: 
1.381     albertel 4090:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4091: 	'<input type="button" value="Save" '.
1.381     albertel 4092: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4093: 	'</form>'."\n";
1.324     albertel 4094:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4095:     $request->print($studentTable);
                   4096: 
                   4097:     return '';
1.119     ng       4098: }
                   4099: 
                   4100: sub displaySubByDates {
1.148     albertel 4101:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4102:     my $isCODE=0;
1.335     albertel 4103:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4104:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4105:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4106: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4107: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4108: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4109: 	'<td><b>Submission</b></td>'.
                   4110: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4111:     my ($version);
                   4112:     my %mark;
1.148     albertel 4113:     my %orders;
1.119     ng       4114:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4115:     if (!exists($$record{'1:timestamp'})) {
1.398     albertel 4116: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
1.147     albertel 4117:     }
1.335     albertel 4118: 
                   4119:     my $interaction;
1.119     ng       4120:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4121: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4122: 	if (exists($$record{$version.':resource.0.version'})) {
                   4123: 	    $interaction = $$record{$version.':resource.0.version'};
                   4124: 	}
                   4125: 
                   4126: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4127: 		             : "$version:resource");
                   4128: 	#&Apache::lonnet::logthis(" got $where");
1.119     ng       4129: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4130: 	if ($isCODE) {
                   4131: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4132: 	}
1.119     ng       4133: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4134: 	my @displaySub = ();
                   4135: 	foreach my $partid (@{$parts}) {
1.335     albertel 4136: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4137: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4138: 	    
                   4139: 
1.122     ng       4140: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4141: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4142: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4143: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4144: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4145: 
                   4146: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4147: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   4148: 		    #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
1.207     albertel 4149: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.398     albertel 4150: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
                   4151: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4152: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4153: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4154: 		    } else {
                   4155: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4156: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4157: 		    }
1.335     albertel 4158: 		    my $responseType=($isTask ? 'Task'
                   4159:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4160: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4161: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4162: 			$orders{$partid}->{$responseId}=
                   4163: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4164: 		    }
1.147     albertel 4165: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4166: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4167: 		}
                   4168: 	    }
1.335     albertel 4169: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4170: 		$displaySub[1].='Checked in by '.
                   4171: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4172: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4173: 		    '<br />';
                   4174: 	    }
                   4175: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4176: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4177: 		    lc($$record{"$where.$partid.award"}).' '.
                   4178: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4179: 		    '<br />';
                   4180: 	    }
1.335     albertel 4181: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4182: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4183: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4184: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4185: 		$displaySub[2].=
                   4186: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4187: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4188: 	    }
                   4189: 	}
                   4190: 	# needed because old essay regrader has not parts info
                   4191: 	if (exists $$record{"$version:resource.regrader"}) {
                   4192: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4193: 	}
                   4194: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4195: 	if ($displaySub[2]) {
                   4196: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4197: 	}
1.382     albertel 4198: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4199:     
1.119     ng       4200:     }
                   4201:     $studentTable.='</table></td></tr></table>';
                   4202:     return $studentTable;
1.71      ng       4203: }
                   4204: 
                   4205: sub updateGradeByPage {
                   4206:     my ($request) = shift;
                   4207: 
1.257     albertel 4208:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4209:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4210:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4211:     my $pageTitle = $env{'form.page'};
1.103     albertel 4212:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4213:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4214:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4215:     if (!&canmodify($usec)) {
1.398     albertel 4216: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4217: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4218: 	return;
                   4219:     }
1.398     albertel 4220:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4221:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4222: 	'</h3>'."\n";
1.70      ng       4223: 
1.68      ng       4224:     $request->print($result);
                   4225: 
1.132     bowersj2 4226:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4227:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4228:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4229:     if (!$map) {
1.398     albertel 4230: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4231: 	my ($symb)=&get_symb($request);
                   4232: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4233: 	return; 
                   4234:     }
1.71      ng       4235:     my $iterator = $navmap->getIterator($map->map_start(),
                   4236: 					$map->map_finish());
1.70      ng       4237: 
1.71      ng       4238:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4239: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4240: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4241: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4242: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4243: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4244: 
                   4245:     $iterator->next(); # skip the first BEGIN_MAP
                   4246:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4247:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4248:     while ($depth > 0) {
1.71      ng       4249:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4250:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4251: 
1.385     albertel 4252:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4253: 	    my $parts = $curRes->parts();
1.71      ng       4254:             my $title = $curRes->compTitle();
                   4255: 	    my $symbx = $curRes->symb();
1.196     albertel 4256: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4257: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4258: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4259: 
                   4260: 	    my %newrecord=();
                   4261: 	    my @displayPts=();
1.269     raeburn  4262:             my %aggregate = ();
                   4263:             my $aggregateflag = 0;
1.71      ng       4264: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4265: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4266: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4267: 
1.257     albertel 4268: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4269: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4270: 		my $partial = $newpts/$wgt;
                   4271: 		my $score;
                   4272: 		if ($partial > 0) {
                   4273: 		    $score = 'correct_by_override';
1.125     ng       4274: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4275: 		    $score = 'incorrect_by_override';
                   4276: 		}
1.257     albertel 4277: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4278: 		if ($dropMenu eq 'excused') {
1.71      ng       4279: 		    $partial = '';
                   4280: 		    $score = 'excused';
1.125     ng       4281: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4282: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4283: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4284: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4285: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4286: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4287: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4288: 		    $changeflag++;
                   4289: 		    $newpts = '';
1.269     raeburn  4290:                     
                   4291:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4292:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4293:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4294:                     if ($aggtries > 0) {
                   4295:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4296:                         $aggregateflag = 1;
                   4297:                     }
1.71      ng       4298: 		}
1.324     albertel 4299: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4300: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4301: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4302: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4303: 		    '&nbsp;<br />';
1.207     albertel 4304: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4305: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4306: 		    '&nbsp;<br />';
1.71      ng       4307: 		$question++;
1.380     albertel 4308: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4309: 
1.71      ng       4310: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4311: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4312: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4313: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4314: 
                   4315: 		$changeflag++;
                   4316: 	    }
                   4317: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4318: 		my %record = 
                   4319: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4320: 					     $udom,$uname);
                   4321: 
                   4322: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4323: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4324: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4325: 		    $newrecord{'resource.CODE'} = '';
                   4326: 		}
1.257     albertel 4327: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4328: 					$udom,$uname);
1.382     albertel 4329: 		%record = &Apache::lonnet::restore($symbx,
                   4330: 						   $env{'request.course.id'},
                   4331: 						   $udom,$uname);
1.380     albertel 4332: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4333: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4334: 	    }
1.380     albertel 4335: 	    
1.269     raeburn  4336:             if ($aggregateflag) {
                   4337:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4338:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4339:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4340:             }
1.125     ng       4341: 
1.71      ng       4342: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4343: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4344: 		'</tr>';
1.68      ng       4345: 
1.196     albertel 4346: 	    $prob++;
1.68      ng       4347: 	}
1.71      ng       4348:         $curRes = $iterator->next();
1.68      ng       4349:     }
1.98      albertel 4350: 
1.71      ng       4351:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4352:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4353:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4354: 		  'The scores were changed for '.
                   4355: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4356:     $request->print($grademsg.$studentTable);
1.68      ng       4357: 
1.70      ng       4358:     return '';
                   4359: }
                   4360: 
1.72      ng       4361: #-------- end of section for handling grading by page/sequence ---------
                   4362: #
                   4363: #-------------------------------------------------------------------
                   4364: 
1.75      albertel 4365: #--------------------Scantron Grading-----------------------------------
                   4366: #
                   4367: #------ start of section for handling grading by page/sequence ---------
                   4368: 
1.81      albertel 4369: sub defaultFormData {
1.324     albertel 4370:     my ($symb)=@_;
1.81      albertel 4371:     return '
                   4372:       <input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.257     albertel 4373:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4374:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4375: }
                   4376: 
1.75      albertel 4377: sub getSequenceDropDown {
                   4378:     my ($request,$symb)=@_;
                   4379:     my $result='<select name="selectpage">'."\n";
                   4380:     my ($titles,$symbx) = &getSymbMap($request);
1.137     albertel 4381:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4382:     my $ctr=0;
                   4383:     foreach (@$titles) {
                   4384: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4385: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4386: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4387: 	    '>'.$showtitle.'</option>'."\n";
                   4388: 	$ctr++;
                   4389:     }
                   4390:     $result.= '</select>';
                   4391:     return $result;
                   4392: }
                   4393: 
1.202     albertel 4394: sub scantron_filenames {
1.257     albertel 4395:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4396:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4397:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4398: 				    &propath($cdom,$cname));
1.202     albertel 4399:     my @possiblenames;
1.201     albertel 4400:     foreach my $filename (sort(@files)) {
1.157     albertel 4401: 	($filename)=split(/&/,$filename);
                   4402: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4403: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4404: 	push(@possiblenames,$filename);
                   4405:     }
                   4406:     return @possiblenames;
                   4407: }
                   4408: 
                   4409: sub scantron_uploads {
1.209     ng       4410:     my ($file2grade) = @_;
1.202     albertel 4411:     my $result=	'<select name="scantron_selectfile">';
                   4412:     $result.="<option></option>";
                   4413:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4414: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4415:     }
                   4416:     $result.="</select>";
                   4417:     return $result;
                   4418: }
                   4419: 
1.82      albertel 4420: sub scantron_scantab {
                   4421:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4422:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4423:     $result.='<option></option>'."\n";
1.82      albertel 4424:     foreach my $line (<$fh>) {
                   4425: 	my ($name,$descrip)=split(/:/,$line);
                   4426: 	if ($name =~ /^\#/) { next; }
                   4427: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4428:     }
                   4429:     $result.='</select>'."\n";
                   4430: 
                   4431:     return $result;
                   4432: }
                   4433: 
1.186     albertel 4434: sub scantron_CODElist {
1.257     albertel 4435:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4436:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4437:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4438:     my $namechoice='<option></option>';
1.225     albertel 4439:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4440: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4441: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4442: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4443:     }
                   4444:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4445:     return $namechoice;
                   4446: }
                   4447: 
                   4448: sub scantron_CODEunique {
1.381     albertel 4449:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4450:                  <label><input type="radio" name="scantron_CODEunique"
1.308     albertel 4451:                         value="yes" checked="checked" /> Yes </label>
1.381     albertel 4452:                 </span>
                   4453:                 <span style="white-space: nowrap;">
1.272     albertel 4454:                  <label><input type="radio" name="scantron_CODEunique"
1.308     albertel 4455:                         value="no" /> No </label>
1.381     albertel 4456:                 </span>';
1.186     albertel 4457:     return $result;
                   4458: }
                   4459: 
1.75      albertel 4460: sub scantron_selectphase {
1.209     ng       4461:     my ($r,$file2grade) = @_;
1.324     albertel 4462:     my ($symb)=&get_symb($r);
1.75      albertel 4463:     if (!$symb) {return '';}
                   4464:     my $sequence_selector=&getSequenceDropDown($r,$symb);
1.324     albertel 4465:     my $default_form_data=&defaultFormData($symb);
                   4466:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4467:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4468:     my $format_selector=&scantron_scantab();
1.186     albertel 4469:     my $CODE_selector=&scantron_CODElist();
                   4470:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4471:     my $result;
1.157     albertel 4472:     #FIXME allow instructor to be able to download the scantron file
                   4473:     # and to upload it,
1.75      albertel 4474:     $result.= <<SCANTRONFORM;
1.162     albertel 4475:     <table width="100%" border="0">
1.75      albertel 4476:     <tr>
1.226     albertel 4477:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4478:       <td bgcolor="#777777">
1.203     albertel 4479:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4480:         $default_form_data
1.75      albertel 4481:         <table width="100%" border="0">
                   4482:           <tr bgcolor="#e6ffff">
1.174     albertel 4483:             <td colspan="2">
                   4484:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4485:             </td>
                   4486:           </tr>
                   4487:           <tr bgcolor="#ffffe6">
1.174     albertel 4488:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4489:           </tr>
                   4490:           <tr bgcolor="#ffffe6">
1.174     albertel 4491:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4492:           </tr>
1.82      albertel 4493:           <tr bgcolor="#ffffe6">
1.174     albertel 4494:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4495:           </tr>
1.157     albertel 4496:           <tr bgcolor="#ffffe6">
1.186     albertel 4497:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4498:           </tr>
                   4499:           <tr bgcolor="#ffffe6">
                   4500:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4501:           </tr>
                   4502:           <tr bgcolor="#ffffe6">
1.187     albertel 4503: 	    <td> Options: </td>
                   4504:             <td>
1.272     albertel 4505: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.331     albertel 4506:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all exisiting corrections</label> <br />
                   4507:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4508: 	    </td>
                   4509:           </tr>
                   4510:           <tr bgcolor="#ffffe6">
1.174     albertel 4511:             <td colspan="2">
1.265     www      4512:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4513:             </td>
                   4514:           </tr>
                   4515:         </table>
1.226     albertel 4516:        </td>
                   4517:      </form>
1.162     albertel 4518:     </tr>
                   4519: SCANTRONFORM
                   4520:    
                   4521:     $r->print($result);
                   4522: 
1.257     albertel 4523:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4524:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4525: 
                   4526:         $r->print(<<SCANTRONFORM);
                   4527:     <tr>
                   4528:       <td bgcolor="#777777">
                   4529:         <table width="100%" border="0">
                   4530:           <tr bgcolor="#e6ffff">
                   4531:             <td>
1.174     albertel 4532:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4533:             </td>
                   4534:           </tr>
                   4535:           <tr bgcolor="#ffffe6">
                   4536:             <td>
                   4537: SCANTRONFORM
1.324     albertel 4538:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4539:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4540:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4541:     $r->print(<<UPLOAD);
                   4542:               <script type="text/javascript" language="javascript">
                   4543:     function checkUpload(formname) {
                   4544: 	if (formname.upfile.value == "") {
                   4545: 	    alert("Please use the browse button to select a file from your local directory.");
                   4546: 	    return false;
                   4547: 	}
                   4548: 	formname.submit();
                   4549:     }
                   4550:               </script>
                   4551: 
                   4552:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4553:                 $default_form_data
                   4554:                 <input name='courseid' type='hidden' value='$cnum' />
                   4555:                 <input name='domainid' type='hidden' value='$cdom' />
                   4556:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4557:                 File to upload:<input type="file" name="upfile" size="50" />
                   4558:                 <br />
                   4559:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4560:               </form>
                   4561: UPLOAD
1.162     albertel 4562: 
                   4563:         $r->print(<<SCANTRONFORM);
                   4564:             </td>
                   4565:           </tr>
1.75      albertel 4566:         </table>
                   4567:       </td>
                   4568:     </tr>
1.162     albertel 4569: SCANTRONFORM
                   4570:     }
1.187     albertel 4571:     $r->print(<<SCANTRONFORM);
                   4572:     <tr>
1.226     albertel 4573:       <form action='/adm/grades' name='scantron_download'>
                   4574:         <td bgcolor="#777777">
1.379     albertel 4575: 	  $default_form_data
1.187     albertel 4576:           <input type="hidden" name="command" value="scantron_download" />
                   4577:           <table width="100%" border="0">
                   4578:             <tr bgcolor="#e6ffff">
                   4579:               <td colspan="2">
                   4580:                 &nbsp;<b>Download a scoring office file</b>
                   4581:               </td>
                   4582:             </tr>
                   4583:             <tr bgcolor="#ffffe6">
                   4584:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4585:             </tr>
                   4586:             <tr bgcolor="#ffffe6">
                   4587:               <td colspan="2">
1.293     www      4588:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4589:               </td>
                   4590:             </tr>
                   4591:           </table>
1.226     albertel 4592:         </td>
                   4593:       </form>
1.187     albertel 4594:     </tr>
                   4595: SCANTRONFORM
1.162     albertel 4596: 
                   4597:     $r->print(<<SCANTRONFORM);
1.75      albertel 4598:   </table>
1.81      albertel 4599: $grading_menu_button
1.75      albertel 4600: SCANTRONFORM
                   4601: 
1.162     albertel 4602:     return
1.75      albertel 4603: }
                   4604: 
1.82      albertel 4605: sub get_scantron_config {
                   4606:     my ($which) = @_;
                   4607:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4608:     my %config;
1.157     albertel 4609:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4610:     foreach my $line (<$fh>) {
                   4611: 	my ($name,$descrip)=split(/:/,$line);
                   4612: 	if ($name ne $which ) { next; }
                   4613: 	chomp($line);
                   4614: 	my @config=split(/:/,$line);
                   4615: 	$config{'name'}=$config[0];
                   4616: 	$config{'description'}=$config[1];
                   4617: 	$config{'CODElocation'}=$config[2];
                   4618: 	$config{'CODEstart'}=$config[3];
                   4619: 	$config{'CODElength'}=$config[4];
                   4620: 	$config{'IDstart'}=$config[5];
                   4621: 	$config{'IDlength'}=$config[6];
                   4622: 	$config{'Qstart'}=$config[7];
                   4623: 	$config{'Qlength'}=$config[8];
                   4624: 	$config{'Qoff'}=$config[9];
                   4625: 	$config{'Qon'}=$config[10];
1.157     albertel 4626: 	$config{'PaperID'}=$config[11];
                   4627: 	$config{'PaperIDlength'}=$config[12];
                   4628: 	$config{'FirstName'}=$config[13];
                   4629: 	$config{'FirstNamelength'}=$config[14];
                   4630: 	$config{'LastName'}=$config[15];
                   4631: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4632: 	last;
                   4633:     }
                   4634:     return %config;
                   4635: }
                   4636: 
                   4637: sub username_to_idmap {
                   4638:     my ($classlist)= @_;
                   4639:     my %idmap;
                   4640:     foreach my $student (keys(%$classlist)) {
                   4641: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4642: 	    $student;
                   4643:     }
                   4644:     return %idmap;
                   4645: }
                   4646: 
1.157     albertel 4647: sub scantron_fixup_scanline {
                   4648:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   4649:     if ($field eq 'ID') {
                   4650: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 4651: 	    return ($line,1,'New value too large');
1.157     albertel 4652: 	}
                   4653: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   4654: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   4655: 				     $args->{'newid'});
                   4656: 	}
                   4657: 	substr($line,$$scantron_config{'IDstart'}-1,
                   4658: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   4659: 	if ($args->{'newid'}=~/^\s*$/) {
                   4660: 	    &scan_data($scan_data,"$whichline.user",
                   4661: 		       $args->{'username'}.':'.$args->{'domain'});
                   4662: 	}
1.186     albertel 4663:     } elsif ($field eq 'CODE') {
1.192     albertel 4664: 	if ($args->{'CODE_ignore_dup'}) {
                   4665: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   4666: 	}
                   4667: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   4668: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 4669: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   4670: 		return ($line,1,'New CODE value too large');
                   4671: 	    }
                   4672: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   4673: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   4674: 	    }
                   4675: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   4676: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 4677: 	}
1.157     albertel 4678:     } elsif ($field eq 'answer') {
                   4679: 	my $length=$scantron_config->{'Qlength'};
                   4680: 	my $off=$scantron_config->{'Qoff'};
                   4681: 	my $on=$scantron_config->{'Qon'};
                   4682: 	my $answer=${off}x$length;
                   4683: 	if ($args->{'response'} eq 'none') {
                   4684: 	    &scan_data($scan_data,
                   4685: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   4686: 	} else {
1.274     albertel 4687: 	    if ($on eq 'letter') {
                   4688: 		my @alphabet=('A'..'Z');
                   4689: 		$answer=$alphabet[$args->{'response'}];
                   4690: 	    } elsif ($on eq 'number') {
                   4691: 		$answer=$args->{'response'}+1;
1.389     albertel 4692: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 4693: 	    } else {
                   4694: 		substr($answer,$args->{'response'},1)=$on;
                   4695: 	    }
1.157     albertel 4696: 	    &scan_data($scan_data,
                   4697: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   4698: 	}
                   4699: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   4700: 	substr($line,$where-1,$length)=$answer;
                   4701:     }
                   4702:     return $line;
                   4703: }
                   4704: 
                   4705: sub scan_data {
                   4706:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 4707:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 4708:     if (defined($value)) {
                   4709: 	$scan_data->{$filename.'_'.$key} = $value;
                   4710:     }
                   4711:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   4712:     return $scan_data->{$filename.'_'.$key};
                   4713: }
                   4714: 
1.82      albertel 4715: sub scantron_parse_scanline {
1.194     albertel 4716:     my ($line,$whichline,$scantron_config,$scan_data,$justHeader)=@_;
1.82      albertel 4717:     my %record;
                   4718:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);
                   4719:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);
1.278     albertel 4720:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   4721: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   4722: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   4723: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   4724: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 4725: 	    $record{'scantron.CODE'}=substr($data,
                   4726: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 4727: 					    $$scantron_config{'CODElength'});
1.191     albertel 4728: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   4729: 		$record{'scantron.useCODE'}=1;
                   4730: 	    }
1.192     albertel 4731: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   4732: 		$record{'scantron.CODE_ignore_dup'}=1;
                   4733: 	    }
1.82      albertel 4734: 	} else {
                   4735: 	    #FIXME interpret first N questions
                   4736: 	}
                   4737:     }
1.83      albertel 4738:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   4739: 				  $$scantron_config{'IDlength'});
1.157     albertel 4740:     $record{'scantron.PaperID'}=
                   4741: 	substr($data,$$scantron_config{'PaperID'}-1,
                   4742: 	       $$scantron_config{'PaperIDlength'});
                   4743:     $record{'scantron.FirstName'}=
                   4744: 	substr($data,$$scantron_config{'FirstName'}-1,
                   4745: 	       $$scantron_config{'FirstNamelength'});
                   4746:     $record{'scantron.LastName'}=
                   4747: 	substr($data,$$scantron_config{'LastName'}-1,
                   4748: 	       $$scantron_config{'LastNamelength'});
1.194     albertel 4749:     if ($justHeader) { return \%record; }
                   4750: 
1.82      albertel 4751:     my @alphabet=('A'..'Z');
                   4752:     my $questnum=0;
                   4753:     while ($questions) {
                   4754: 	$questnum++;
                   4755: 	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
                   4756: 	substr($questions,0,$$scantron_config{'Qlength'})='';
1.83      albertel 4757: 	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
1.239     albertel 4758: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.371     albertel 4759: 	    if ($currentquest eq '?'
                   4760: 		|| $currentquest eq '*') {
1.274     albertel 4761: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4762: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 4763: 	    } elsif (!defined($currentquest)
1.274     albertel 4764: 		     || $currentquest eq $$scantron_config{'Qoff'}
                   4765: 		     || $currentquest !~ /^[A-Z]$/) {
1.239     albertel 4766: 		$record{"scantron.$questnum.answer"}='';
                   4767: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4768: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4769: 		}
                   4770: 	    } else {
                   4771: 		$record{"scantron.$questnum.answer"}=$currentquest;
                   4772: 	    }
                   4773: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.371     albertel 4774: 	    if ($currentquest eq '?'
                   4775: 		|| $currentquest eq '*') {
1.274     albertel 4776: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4777: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 4778: 	    } elsif (!defined($currentquest)
                   4779: 		     || $currentquest eq $$scantron_config{'Qoff'} 
                   4780: 		     || $currentquest !~ /^\d$/) {
1.239     albertel 4781: 		$record{"scantron.$questnum.answer"}='';
                   4782: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4783: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4784: 		}
                   4785: 	    } else {
1.371     albertel 4786: 		# wrap zero back to J
                   4787: 		if ($currentquest eq '0') {
                   4788: 		    $record{"scantron.$questnum.answer"}=
                   4789: 			$alphabet[9];
                   4790: 		} else {
                   4791: 		    $record{"scantron.$questnum.answer"}=
                   4792: 			$alphabet[$currentquest-1];
                   4793: 		}
1.239     albertel 4794: 	    }
1.82      albertel 4795: 	} else {
1.239     albertel 4796: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
                   4797: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}) {
                   4798: 		$record{"scantron.$questnum.answer"}='';
                   4799: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4800: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4801: 		}
                   4802: 	    } else {
                   4803: 		$record{"scantron.$questnum.answer"}=
                   4804: 		    $alphabet[length($array[0])];
                   4805: 	    }
                   4806: 	    if (scalar(@array) gt 2) {
                   4807: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4808: 		my @ans=@array;
                   4809: 		my $i=length($ans[0]);shift(@ans);
                   4810: 		while ($#ans) {
                   4811: 		    $i+=length($ans[0])+1;
                   4812: 		    $record{"scantron.$questnum.answer"}.=$alphabet[$i];
                   4813: 		    shift(@ans);
                   4814: 		}
                   4815: 	    }
1.82      albertel 4816: 	}
                   4817:     }
1.83      albertel 4818:     $record{'scantron.maxquest'}=$questnum;
                   4819:     return \%record;
1.82      albertel 4820: }
                   4821: 
                   4822: sub scantron_add_delay {
1.140     albertel 4823:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   4824:     push(@$delayqueue,
                   4825: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   4826: 	  'ecode' => $errorcode }
                   4827: 	 );
1.82      albertel 4828: }
                   4829: 
                   4830: sub scantron_find_student {
1.157     albertel 4831:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 4832:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 4833:     if ($scanID =~ /^\s*$/) {
                   4834:  	return &scan_data($scan_data,"$line.user");
                   4835:     }
1.83      albertel 4836:     foreach my $id (keys(%$idmap)) {
1.157     albertel 4837:  	if (lc($id) eq lc($scanID)) {
                   4838:  	    return $$idmap{$id};
                   4839:  	}
1.83      albertel 4840:     }
                   4841:     return undef;
                   4842: }
                   4843: 
                   4844: sub scantron_filter {
                   4845:     my ($curres)=@_;
1.331     albertel 4846: 
                   4847:     if (ref($curres) && $curres->is_problem()) {
                   4848: 	# if the user has asked to not have either hidden
                   4849: 	# or 'randomout' controlled resources to be graded
                   4850: 	# don't include them
                   4851: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   4852: 	    && $curres->randomout) {
                   4853: 	    return 0;
                   4854: 	}
1.83      albertel 4855: 	return 1;
                   4856:     }
                   4857:     return 0;
1.82      albertel 4858: }
                   4859: 
1.157     albertel 4860: sub scantron_process_corrections {
                   4861:     my ($r) = @_;
1.257     albertel 4862:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 4863:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4864:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 4865:     my $which=$env{'form.scantron_line'};
1.200     albertel 4866:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 4867:     my ($skip,$err,$errmsg);
1.257     albertel 4868:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 4869: 	$skip=1;
1.257     albertel 4870:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   4871: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   4872: 	    $env{'form.scantron_domain'};
1.157     albertel 4873: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   4874: 	($line,$err,$errmsg)=
                   4875: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   4876: 				     'ID',{'newid'=>$newid,
1.257     albertel 4877: 				    'username'=>$env{'form.scantron_username'},
                   4878: 				    'domain'=>$env{'form.scantron_domain'}});
                   4879:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   4880: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 4881: 	my $newCODE;
1.192     albertel 4882: 	my %args;
1.190     albertel 4883: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 4884: 	    $newCODE='use_unfound';
1.190     albertel 4885: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 4886: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 4887: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 4888: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 4889: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 4890: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 4891: 	}
1.257     albertel 4892: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 4893: 	    $args{'CODE_ignore_dup'}=1;
                   4894: 	}
                   4895: 	$args{'CODE'}=$newCODE;
1.186     albertel 4896: 	($line,$err,$errmsg)=
                   4897: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 4898: 				     'CODE',\%args);
1.257     albertel 4899:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   4900: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 4901: 	    ($line,$err,$errmsg)=
                   4902: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   4903: 					 $which,'answer',
                   4904: 					 { 'question'=>$question,
1.257     albertel 4905: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 4906: 	    if ($err) { last; }
                   4907: 	}
                   4908:     }
                   4909:     if ($err) {
1.398     albertel 4910: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 4911:     } else {
1.200     albertel 4912: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 4913: 	&scantron_putfile($scanlines,$scan_data);
                   4914:     }
                   4915: }
                   4916: 
1.200     albertel 4917: sub reset_skipping_status {
                   4918:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4919:     &scan_data($scan_data,'remember_skipping',undef,1);
                   4920:     &scantron_putfile(undef,$scan_data);
                   4921: }
                   4922: 
1.376     albertel 4923: sub start_skipping {
1.200     albertel 4924:     my ($scan_data,$i)=@_;
                   4925:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 4926:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   4927: 	$remembered{$i}=2;
                   4928:     } else {
                   4929: 	$remembered{$i}=1;
                   4930:     }
1.200     albertel 4931:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   4932: }
                   4933: 
                   4934: sub should_be_skipped {
1.376     albertel 4935:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 4936:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 4937: 	# not redoing old skips
1.376     albertel 4938: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 4939: 	return 0;
                   4940:     }
                   4941:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 4942: 
                   4943:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   4944: 	return 0;
                   4945:     }
1.200     albertel 4946:     return 1;
                   4947: }
                   4948: 
                   4949: sub remember_current_skipped {
                   4950:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4951:     my %to_remember;
                   4952:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   4953: 	if ($scanlines->{'skipped'}[$i]) {
                   4954: 	    $to_remember{$i}=1;
                   4955: 	}
                   4956:     }
1.376     albertel 4957: 
1.200     albertel 4958:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   4959:     &scantron_putfile(undef,$scan_data);
                   4960: }
                   4961: 
                   4962: sub check_for_error {
                   4963:     my ($r,$result)=@_;
                   4964:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 4965: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 4966:     }
                   4967: }
1.157     albertel 4968: 
1.203     albertel 4969: sub scantron_warning_screen {
                   4970:     my ($button_text)=@_;
1.257     albertel 4971:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 4972:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 4973:     my $CODElist;
1.284     albertel 4974:     if ($scantron_config{'CODElocation'} &&
                   4975: 	$scantron_config{'CODEstart'} &&
                   4976: 	$scantron_config{'CODElength'}) {
                   4977: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 4978: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 4979: 	$CODElist=
                   4980: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 4981: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 4982:     }
1.203     albertel 4983:     return (<<STUFF);
                   4984: <p>
1.398     albertel 4985: <span class="LC_warning">Please double check the information
                   4986:                  below before clicking on '$button_text'</span>
1.203     albertel 4987: </p>
                   4988: <table>
1.284     albertel 4989: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 4990: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 4991: $CODElist
1.203     albertel 4992: </table>
                   4993: <br />
                   4994: <p> If this information is correct, please click on '$button_text'.</p>
                   4995: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   4996: 
                   4997: <br />
                   4998: STUFF
                   4999: }
                   5000: 
                   5001: sub scantron_do_warning {
                   5002:     my ($r)=@_;
1.324     albertel 5003:     my ($symb)=&get_symb($r);
1.203     albertel 5004:     if (!$symb) {return '';}
1.324     albertel 5005:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5006:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5007:     if ( $env{'form.selectpage'} eq '' ||
                   5008: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5009: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5010: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5011: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5012: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5013: 	} 
1.257     albertel 5014: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5015: 	    $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
1.237     albertel 5016: 	} 
1.257     albertel 5017: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5018: 	    $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
1.237     albertel 5019: 	} 
                   5020:     } else {
1.265     www      5021: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5022: 	$r->print(<<STUFF);
1.203     albertel 5023: $warning
1.265     www      5024: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5025: <input type="hidden" name="command" value="scantron_validate" />
                   5026: STUFF
1.237     albertel 5027:     }
1.352     albertel 5028:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5029:     return '';
                   5030: }
                   5031: 
                   5032: sub scantron_form_start {
                   5033:     my ($max_bubble)=@_;
                   5034:     my $result= <<SCANTRONFORM;
                   5035: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5036:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5037:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5038:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5039:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5040:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5041:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5042:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5043:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5044:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5045: SCANTRONFORM
                   5046:     return $result;
                   5047: }
                   5048: 
1.157     albertel 5049: sub scantron_validate_file {
                   5050:     my ($r) = @_;
1.324     albertel 5051:     my ($symb)=&get_symb($r);
1.157     albertel 5052:     if (!$symb) {return '';}
1.324     albertel 5053:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5054:     
                   5055:     # do the detection of only doing skipped records first befroe we delete
                   5056:     # them  when doing the corrections reset
1.257     albertel 5057:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5058: 	&reset_skipping_status();
                   5059:     }
1.257     albertel 5060:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5061: 	&remember_current_skipped();
1.257     albertel 5062: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5063:     }
                   5064: 
1.257     albertel 5065:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5066: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5067: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5068: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5069: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5070:     }
1.200     albertel 5071: 
1.257     albertel 5072:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5073: 	&scantron_process_corrections($r);
                   5074:     }
1.191     albertel 5075:     $r->print("<p>Gathering neccessary info.</p>");$r->rflush();
1.157     albertel 5076:     #get the student pick code ready
                   5077:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5078:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5079:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5080:     $r->print($result);
                   5081:     
1.334     albertel 5082:     my @validate_phases=( 'sequence',
                   5083: 			  'ID',
1.157     albertel 5084: 			  'CODE',
                   5085: 			  'doublebubble',
                   5086: 			  'missingbubbles');
1.257     albertel 5087:     if (!$env{'form.validatepass'}) {
                   5088: 	$env{'form.validatepass'} = 0;
1.157     albertel 5089:     }
1.257     albertel 5090:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5091: 
                   5092:     my $stop=0;
                   5093:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5094: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5095: 	$r->rflush();
                   5096: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5097: 	{
                   5098: 	    no strict 'refs';
                   5099: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5100: 	}
                   5101:     }
                   5102:     if (!$stop) {
1.203     albertel 5103: 	my $warning=&scantron_warning_screen('Start Grading');
                   5104: 	$r->print(<<STUFF);
                   5105: Validation process complete.<br />
                   5106: $warning
                   5107: <input type="submit" name="submit" value="Start Grading" />
                   5108: <input type="hidden" name="command" value="scantron_process" />
                   5109: STUFF
                   5110: 
1.157     albertel 5111:     } else {
                   5112: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5113: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5114:     }
                   5115:     if ($stop) {
1.334     albertel 5116: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5117: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5118: 	    $r->print(' this error <br />');
                   5119: 
                   5120: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5121: 	} else {
                   5122: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5123: 	    $r->print(' using corrected info <br />');
                   5124: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5125: 	    $r->print(" this scanline saving it for later.");
                   5126: 	}
1.157     albertel 5127:     }
1.352     albertel 5128:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5129:     return '';
                   5130: }
                   5131: 
1.200     albertel 5132: sub scantron_remove_file {
1.192     albertel 5133:     my ($which)=@_;
1.257     albertel 5134:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5135:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5136:     my $file='scantron_';
1.200     albertel 5137:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5138: 	$file.=$which.'_';
1.192     albertel 5139:     } else {
                   5140: 	return 'refused';
                   5141:     }
1.257     albertel 5142:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5143:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5144: }
                   5145: 
                   5146: sub scantron_remove_scan_data {
1.257     albertel 5147:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5148:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5149:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5150:     my @todelete;
1.257     albertel 5151:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5152:     foreach my $key (@keys) {
                   5153: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5154: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5155: 		$key=~/remember_skipping/) {
                   5156: 		next;
                   5157: 	    }
1.192     albertel 5158: 	    push(@todelete,$key);
                   5159: 	}
                   5160:     }
1.200     albertel 5161:     my $result;
1.192     albertel 5162:     if (@todelete) {
1.200     albertel 5163: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5164:     }
                   5165:     return $result;
                   5166: }
                   5167: 
1.157     albertel 5168: sub scantron_getfile {
1.200     albertel 5169:     #FIXME really would prefer a scantron directory
1.257     albertel 5170:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5171:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5172:     my $lines;
                   5173:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5174: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5175:     my %scanlines;
                   5176:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5177:     my $temp=$scanlines{'orig'};
                   5178:     $scanlines{'count'}=$#$temp;
                   5179: 
                   5180:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5181: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5182:     if ($lines eq '-1') {
                   5183: 	$scanlines{'corrected'}=[];
                   5184:     } else {
                   5185: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5186:     }
                   5187:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5188: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5189:     if ($lines eq '-1') {
                   5190: 	$scanlines{'skipped'}=[];
                   5191:     } else {
                   5192: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5193:     }
1.175     albertel 5194:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5195:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5196:     my %scan_data = @tmp;
                   5197:     return (\%scanlines,\%scan_data);
                   5198: }
                   5199: 
                   5200: sub lonnet_putfile {
                   5201:     my ($contents,$filename)=@_;
1.257     albertel 5202:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5203:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5204:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 5205:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 5206: 
                   5207: }
                   5208: 
                   5209: sub scantron_putfile {
                   5210:     my ($scanlines,$scan_data) = @_;
1.200     albertel 5211:     #FIXME really would prefer a scantron directory
1.257     albertel 5212:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5213:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 5214:     if ($scanlines) {
                   5215: 	my $prefix='scantron_';
1.157     albertel 5216: # no need to update orig, shouldn't change
                   5217: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 5218: #		    $env{'form.scantron_selectfile'});
1.200     albertel 5219: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   5220: 			$prefix.'corrected_'.
1.257     albertel 5221: 			$env{'form.scantron_selectfile'});
1.200     albertel 5222: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   5223: 			$prefix.'skipped_'.
1.257     albertel 5224: 			$env{'form.scantron_selectfile'});
1.200     albertel 5225:     }
1.175     albertel 5226:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 5227: }
                   5228: 
                   5229: sub scantron_get_line {
1.200     albertel 5230:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 5231:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   5232:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 5233:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   5234:     return $scanlines->{'orig'}[$i]; 
                   5235: }
                   5236: 
1.200     albertel 5237: sub get_todo_count {
                   5238:     my ($scanlines,$scan_data)=@_;
                   5239:     my $count=0;
                   5240:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5241: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   5242: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5243: 	$count++;
                   5244:     }
                   5245:     return $count;
                   5246: }
                   5247: 
1.157     albertel 5248: sub scantron_put_line {
1.200     albertel 5249:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 5250:     if ($skip) {
                   5251: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 5252: 	&start_skipping($scan_data,$i);
1.157     albertel 5253: 	return;
                   5254:     }
                   5255:     $scanlines->{'corrected'}[$i]=$newline;
                   5256: }
                   5257: 
1.376     albertel 5258: sub scantron_clear_skip {
                   5259:     my ($scanlines,$scan_data,$i)=@_;
                   5260:     if (exists($scanlines->{'skipped'}[$i])) {
                   5261: 	undef($scanlines->{'skipped'}[$i]);
                   5262: 	return 1;
                   5263:     }
                   5264:     return 0;
                   5265: }
                   5266: 
1.334     albertel 5267: sub scantron_filter_not_exam {
                   5268:     my ($curres)=@_;
                   5269:     
                   5270:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   5271: 	# if the user has asked to not have either hidden
                   5272: 	# or 'randomout' controlled resources to be graded
                   5273: 	# don't include them
                   5274: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5275: 	    && $curres->randomout) {
                   5276: 	    return 0;
                   5277: 	}
                   5278: 	return 1;
                   5279:     }
                   5280:     return 0;
                   5281: }
                   5282: 
                   5283: sub scantron_validate_sequence {
                   5284:     my ($r,$currentphase) = @_;
                   5285: 
                   5286:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5287:     my (undef,undef,$sequence)=
                   5288: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   5289: 
                   5290:     my $map=$navmap->getResourceByUrl($sequence);
                   5291: 
                   5292:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   5293:                                     value="ignore" />');
                   5294:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   5295: 	my @resources=
                   5296: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   5297: 	if (@resources) {
1.357     banghart 5298: 	    $r->print("<p>".&mt('Some resources in the sequence currently are not set to exam mode. Grading these resources currently may not work correctly.')."</p>");
1.334     albertel 5299: 	    return (1,$currentphase);
                   5300: 	}
                   5301:     }
                   5302: 
                   5303:     return (0,$currentphase+1);
                   5304: }
                   5305: 
1.157     albertel 5306: sub scantron_validate_ID {
                   5307:     my ($r,$currentphase) = @_;
                   5308:     
                   5309:     #get student info
                   5310:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5311:     my %idmap=&username_to_idmap($classlist);
                   5312: 
                   5313:     #get scantron line setup
1.257     albertel 5314:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5315:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5316: 
                   5317:     my %found=('ids'=>{},'usernames'=>{});
                   5318:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5319: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5320: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5321: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5322: 						 $scan_data);
                   5323: 	my $id=$$scan_record{'scantron.ID'};
                   5324: 	my $found;
                   5325: 	foreach my $checkid (keys(%idmap)) {
                   5326: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   5327: 	}
                   5328: 	if ($found) {
                   5329: 	    my $username=$idmap{$found};
                   5330: 	    if ($found{'ids'}{$found}) {
                   5331: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5332: 					 $line,'duplicateID',$found);
1.194     albertel 5333: 		return(1,$currentphase);
1.157     albertel 5334: 	    } elsif ($found{'usernames'}{$username}) {
                   5335: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5336: 					 $line,'duplicateID',$username);
1.194     albertel 5337: 		return(1,$currentphase);
1.157     albertel 5338: 	    }
1.186     albertel 5339: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 5340: 	    $found{'ids'}{$found}++;
                   5341: 	    $found{'usernames'}{$username}++;
                   5342: 	} else {
                   5343: 	    if ($id =~ /^\s*$/) {
1.158     albertel 5344: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 5345: 		if (defined($username) && $found{'usernames'}{$username}) {
                   5346: 		    &scantron_get_correction($r,$i,$scan_record,
                   5347: 					     \%scantron_config,
                   5348: 					     $line,'duplicateID',$username);
1.194     albertel 5349: 		    return(1,$currentphase);
1.157     albertel 5350: 		} elsif (!defined($username)) {
                   5351: 		    &scantron_get_correction($r,$i,$scan_record,
                   5352: 					     \%scantron_config,
                   5353: 					     $line,'incorrectID');
1.194     albertel 5354: 		    return(1,$currentphase);
1.157     albertel 5355: 		}
                   5356: 		$found{'usernames'}{$username}++;
                   5357: 	    } else {
                   5358: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5359: 					 $line,'incorrectID');
1.194     albertel 5360: 		return(1,$currentphase);
1.157     albertel 5361: 	    }
                   5362: 	}
                   5363:     }
                   5364: 
                   5365:     return (0,$currentphase+1);
                   5366: }
                   5367: 
                   5368: sub scantron_get_correction {
                   5369:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   5370: 
                   5371: #FIXME in the case of a duplicated ID the previous line, probaly need
                   5372: #to show both the current line and the previous one and allow skipping
                   5373: #the previous one or the current one
                   5374: 
1.161     albertel 5375:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 5376:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 5377: 	$r->print(" for PaperID <tt>".
                   5378: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   5379:     } else {
                   5380: 	$r->print(" in scanline $i <pre>".
                   5381: 		  $line."</pre> \n");
                   5382:     }
1.242     albertel 5383:     my $message="<p>The ID on the form is  <tt>".
                   5384: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   5385: 	"The name on the paper is ".
                   5386: 	$$scan_record{'scantron.LastName'}.",".
                   5387: 	$$scan_record{'scantron.FirstName'}."</p>";
                   5388: 
1.157     albertel 5389:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   5390:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   5391:     if ($error =~ /ID$/) {
1.186     albertel 5392: 	if ($error eq 'incorrectID') {
1.157     albertel 5393: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   5394: 	} elsif ($error eq 'duplicateID') {
                   5395: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   5396: 	}
1.242     albertel 5397: 	$r->print($message);
1.157     albertel 5398: 	$r->print("<p>How should I handle this? <br /> \n");
                   5399: 	$r->print("\n<ul><li> ");
                   5400: 	#FIXME it would be nice if this sent back the user ID and
                   5401: 	#could do partial userID matches
                   5402: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   5403: 				       'scantron_username','scantron_domain'));
                   5404: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   5405: 	$r->print("\n@".
1.257     albertel 5406: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 5407: 
                   5408: 	$r->print('</li>');
1.186     albertel 5409:     } elsif ($error =~ /CODE$/) {
                   5410: 	if ($error eq 'incorrectCODE') {
1.187     albertel 5411: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 5412: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 5413: 	    $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 5414: 	}
1.224     albertel 5415: 	$r->print("<p>The CODE on the form is  <tt>'".
                   5416: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 5417: 	$r->print($message);
1.186     albertel 5418: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 5419: 	$r->print("\n<br /> ");
1.194     albertel 5420: 	my $i=0;
1.273     albertel 5421: 	if ($error eq 'incorrectCODE' 
                   5422: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 5423: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 5424: 	    if ($closest > 0) {
                   5425: 		foreach my $testcode (@{$closest}) {
                   5426: 		    my $checked='';
1.401     albertel 5427: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 5428: 		    $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' />");
                   5429: 		    $r->print("\n<br />");
                   5430: 		    $i++;
                   5431: 		}
1.194     albertel 5432: 	    }
                   5433: 	}
1.273     albertel 5434: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 5435: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 5436: 	    $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>");
                   5437: 	    $r->print("\n<br />");
                   5438: 	}
1.194     albertel 5439: 
1.188     albertel 5440: 	$r->print(<<ENDSCRIPT);
                   5441: <script type="text/javascript">
                   5442: function change_radio(field) {
1.190     albertel 5443:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 5444:     var i;
                   5445:     for (i=0;i<slct.length;i++) {
                   5446:         if (slct[i].value==field) { slct[i].checked=true; }
                   5447:     }
                   5448: }
                   5449: </script>
                   5450: ENDSCRIPT
1.187     albertel 5451: 	my $href="/adm/pickcode?".
1.359     www      5452: 	   "form=".&escape("scantronupload").
                   5453: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   5454: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   5455: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   5456: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 5457: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   5458: 	    $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')\" />");
                   5459: 	    $r->print("\n<br />");
                   5460: 	}
1.272     albertel 5461: 	$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 5462: 	$r->print("\n<br /><br />");
1.157     albertel 5463:     } elsif ($error eq 'doublebubble') {
                   5464: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   5465: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   5466: 		  join(',',@{$arg}).'" />');
1.242     albertel 5467: 	$r->print($message);
1.157     albertel 5468: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   5469: 	foreach my $question (@{$arg}) {
                   5470: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   5471: 	    &scantron_bubble_selector($r,$scan_config,$question,split('',$selected));
                   5472: 	}
                   5473:     } elsif ($error eq 'missingbubble') {
                   5474: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 5475: 	$r->print($message);
1.157     albertel 5476: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   5477: 	$r->print("Some questions have no scanned bubbles\n");
                   5478: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   5479: 		  join(',',@{$arg}).'" />');
                   5480: 	foreach my $question (@{$arg}) {
                   5481: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   5482: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   5483: 	}
                   5484:     } else {
                   5485: 	$r->print("\n<ul>");
                   5486:     }
                   5487:     $r->print("\n</li></ul>");
                   5488: 
                   5489: }
                   5490: 
                   5491: sub scantron_bubble_selector {
                   5492:     my ($r,$scan_config,$quest,@selected)=@_;
                   5493:     my $max=$$scan_config{'Qlength'};
1.274     albertel 5494: 
                   5495:     my $scmode=$$scan_config{'Qon'};
                   5496:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   5497: 
1.157     albertel 5498:     my @alphabet=('A'..'Z');
                   5499:     $r->print("<table border='1'><tr><td rowspan='2'>$quest</td>");
                   5500:     for (my $i=0;$i<$max+1;$i++) {
1.274     albertel 5501: 	$r->print("\n".'<td align="center">');
1.157     albertel 5502: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   5503: 	else { $r->print('&nbsp;'); }
                   5504: 	$r->print('</td>');
                   5505:     }
1.274     albertel 5506:     $r->print('</tr><tr>');
1.157     albertel 5507:     for (my $i=0;$i<$max;$i++) {
1.274     albertel 5508: 	$r->print("\n".
                   5509: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
1.272     albertel 5510: 		  $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
1.157     albertel 5511:     }
1.272     albertel 5512:     $r->print('<td><label><input type="radio" name="scantron_correct_Q_'.
                   5513: 	      $quest.'" value="none" /> No bubble </label></td>');
1.157     albertel 5514:     $r->print('</tr></table>');
                   5515: }
                   5516: 
1.194     albertel 5517: sub num_matches {
                   5518:     my ($orig,$code) = @_;
                   5519:     my @code=split(//,$code);
                   5520:     my @orig=split(//,$orig);
                   5521:     my $same=0;
                   5522:     for (my $i=0;$i<scalar(@code);$i++) {
                   5523: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   5524:     }
                   5525:     return $same;
                   5526: }
                   5527: 
                   5528: sub scantron_get_closely_matching_CODEs {
                   5529:     my ($allcodes,$CODE)=@_;
                   5530:     my @CODEs;
                   5531:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   5532: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   5533:     }
                   5534: 
                   5535:     return ($#CODEs,$CODEs[-1]);
                   5536: }
                   5537: 
                   5538: sub get_codes {
1.280     foxr     5539:     my ($old_name, $cdom, $cnum) = @_;
                   5540:     if (!$old_name) {
                   5541: 	$old_name=$env{'form.scantron_CODElist'};
                   5542:     }
                   5543:     if (!$cdom) {
                   5544: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5545:     }
                   5546:     if (!$cnum) {
                   5547: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   5548:     }
1.278     albertel 5549:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   5550: 				    $cdom,$cnum);
                   5551:     my %allcodes;
                   5552:     if ($result{"type\0$old_name"} eq 'number') {
                   5553: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   5554:     } else {
                   5555: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   5556:     }
1.194     albertel 5557:     return %allcodes;
                   5558: }
                   5559: 
1.157     albertel 5560: sub scantron_validate_CODE {
                   5561:     my ($r,$currentphase) = @_;
1.257     albertel 5562:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 5563:     if ($scantron_config{'CODElocation'} &&
                   5564: 	$scantron_config{'CODEstart'} &&
                   5565: 	$scantron_config{'CODElength'}) {
1.257     albertel 5566: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 5567: 	    &FIXME_blow_up()
                   5568: 	}
                   5569:     } else {
                   5570: 	return (0,$currentphase+1);
                   5571:     }
                   5572:     
                   5573:     my %usedCODEs;
                   5574: 
1.194     albertel 5575:     my %allcodes=&get_codes();
1.186     albertel 5576: 
                   5577:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5578:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5579: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 5580: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5581: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5582: 						 $scan_data);
                   5583: 	my $CODE=$$scan_record{'scantron.CODE'};
                   5584: 	my $error=0;
1.224     albertel 5585: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   5586: 	    &scantron_get_correction($r,$i,$scan_record,
                   5587: 				     \%scantron_config,
                   5588: 				     $line,'incorrectCODE',\%allcodes);
                   5589: 	    return(1,$currentphase);
                   5590: 	}
1.221     albertel 5591: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   5592: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 5593: 	    &scantron_get_correction($r,$i,$scan_record,
                   5594: 				     \%scantron_config,
1.194     albertel 5595: 				     $line,'incorrectCODE',\%allcodes);
                   5596: 	    return(1,$currentphase);
1.186     albertel 5597: 	}
1.214     albertel 5598: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 5599: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 5600: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 5601: 	    &scantron_get_correction($r,$i,$scan_record,
                   5602: 				     \%scantron_config,
1.194     albertel 5603: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   5604: 	    return(1,$currentphase);
1.186     albertel 5605: 	}
1.194     albertel 5606: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 5607:     }
1.157     albertel 5608:     return (0,$currentphase+1);
                   5609: }
                   5610: 
                   5611: sub scantron_validate_doublebubble {
                   5612:     my ($r,$currentphase) = @_;
                   5613:     #get student info
                   5614:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5615:     my %idmap=&username_to_idmap($classlist);
                   5616: 
                   5617:     #get scantron line setup
1.257     albertel 5618:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5619:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5620:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5621: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5622: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5623: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5624: 						 $scan_data);
                   5625: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   5626: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   5627: 				 'doublebubble',
                   5628: 				 $$scan_record{'scantron.doubleerror'});
                   5629:     	return (1,$currentphase);
                   5630:     }
                   5631:     return (0,$currentphase+1);
                   5632: }
                   5633: 
1.330     albertel 5634: sub scantron_get_maxbubble {    
1.257     albertel 5635:     if (defined($env{'form.scantron_maxbubble'}) &&
                   5636: 	$env{'form.scantron_maxbubble'}) {
                   5637: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 5638:     }
1.330     albertel 5639: 
1.191     albertel 5640:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5641:     my (undef,undef,$sequence)=
1.257     albertel 5642: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 5643: 
1.191     albertel 5644:     my $map=$navmap->getResourceByUrl($sequence);
                   5645:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 5646: 
                   5647:     &Apache::lonxml::clear_problem_counter();
                   5648: 
1.191     albertel 5649:     foreach my $resource (@resources) {
1.330     albertel 5650: 	my $result=&Apache::lonnet::ssi($resource->src(),
                   5651: 					('symb' => $resource->symb()));
1.191     albertel 5652:     }
                   5653:     &Apache::lonnet::delenv('scantron\.');
1.330     albertel 5654:     $env{'form.scantron_maxbubble'} =
                   5655: 	&Apache::lonxml::get_problem_counter()-1;
                   5656: 
1.257     albertel 5657:     return $env{'form.scantron_maxbubble'};
1.191     albertel 5658: }
                   5659: 
1.157     albertel 5660: sub scantron_validate_missingbubbles {
                   5661:     my ($r,$currentphase) = @_;
                   5662:     #get student info
                   5663:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5664:     my %idmap=&username_to_idmap($classlist);
                   5665: 
                   5666:     #get scantron line setup
1.257     albertel 5667:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5668:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 5669:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 5670:     if (!$max_bubble) { $max_bubble=2**31; }
                   5671:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5672: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5673: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5674: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5675: 						 $scan_data);
                   5676: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   5677: 	my @to_correct;
                   5678: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   5679: 	    if ($missing > $max_bubble) { next; }
                   5680: 	    push(@to_correct,$missing);
                   5681: 	}
                   5682: 	if (@to_correct) {
                   5683: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5684: 				     $line,'missingbubble',\@to_correct);
                   5685: 	    return (1,$currentphase);
                   5686: 	}
                   5687: 
                   5688:     }
                   5689:     return (0,$currentphase+1);
                   5690: }
                   5691: 
1.82      albertel 5692: sub scantron_process_students {
1.75      albertel 5693:     my ($r) = @_;
1.257     albertel 5694:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 5695:     my ($symb)=&get_symb($r);
1.81      albertel 5696:     if (!$symb) {return '';}
1.324     albertel 5697:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 5698: 
1.257     albertel 5699:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5700:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 5701:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5702:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 5703:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 5704:     my $map=$navmap->getResourceByUrl($sequence);
                   5705:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 5706: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 5707:     my $result= <<SCANTRONFORM;
1.81      albertel 5708: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   5709:   <input type="hidden" name="command" value="scantron_configphase" />
                   5710:   $default_form_data
                   5711: SCANTRONFORM
1.82      albertel 5712:     $r->print($result);
                   5713: 
                   5714:     my @delayqueue;
1.140     albertel 5715:     my %completedstudents;
                   5716:     
1.200     albertel 5717:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 5718:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 5719:  				    'Scantron Progress',$count,
1.195     albertel 5720: 				    'inline',undef,'scantronupload');
1.140     albertel 5721:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   5722: 					  'Processing first student');
                   5723:     my $start=&Time::HiRes::time();
1.158     albertel 5724:     my $i=-1;
1.200     albertel 5725:     my ($uname,$udom,$started);
1.157     albertel 5726:     while ($i<$scanlines->{'count'}) {
                   5727:  	($uname,$udom)=('','');
                   5728:  	$i++;
1.200     albertel 5729:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5730:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 5731: 	if ($started) {
                   5732: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   5733: 						     'last student');
                   5734: 	}
                   5735: 	$started=1;
1.157     albertel 5736:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5737:  						 $scan_data);
                   5738:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   5739:  					      \%idmap,$i)) {
                   5740:   	    &scantron_add_delay(\@delayqueue,$line,
                   5741:  				'Unable to find a student that matches',1);
                   5742:  	    next;
                   5743:   	}
                   5744:  	if (exists $completedstudents{$uname}) {
                   5745:  	    &scantron_add_delay(\@delayqueue,$line,
                   5746:  				'Student '.$uname.' has multiple sheets',2);
                   5747:  	    next;
                   5748:  	}
                   5749:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 5750: 
                   5751: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 5752:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 5753: 
                   5754: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   5755: 	    &scantron_putfile($scanlines,$scan_data);
                   5756: 	}
1.161     albertel 5757: 	
                   5758: 	my $i=0;
1.83      albertel 5759: 	foreach my $resource (@resources) {
1.85      albertel 5760: 	    $i++;
1.193     albertel 5761: 	    my %form=('submitted'     =>'scantron',
                   5762: 		      'grade_target'  =>'grade',
                   5763: 		      'grade_username'=>$uname,
                   5764: 		      'grade_domain'  =>$udom,
1.257     albertel 5765: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 5766: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 5767: 	    if (exists($scan_record->{'scantron.CODE'})
                   5768: 		&& 
                   5769: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 5770: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 5771: 	    } else {
                   5772: 		$form{'CODE'}='';
1.193     albertel 5773: 	    }
                   5774: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 5775: 	    if ($result ne '') {
                   5776: 		&Apache::lonnet::logthis("scantron grading error -> $result");
1.257     albertel 5777: 		&Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
1.227     albertel 5778: 	    }
1.213     albertel 5779: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 5780: 	}
1.140     albertel 5781: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 5782: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 5783:     } continue {
1.330     albertel 5784: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 5785: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 5786:     }
1.140     albertel 5787:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 5788: #    my $lasttime = &Time::HiRes::time()-$start;
                   5789: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 5790: 
1.200     albertel 5791:     $r->print("</form>");
1.324     albertel 5792:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 5793:     return '';
1.75      albertel 5794: }
1.157     albertel 5795: 
                   5796: sub scantron_upload_scantron_data {
                   5797:     my ($r)=@_;
1.257     albertel 5798:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 5799:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 5800: 							  'domainid',
                   5801: 							  'coursename');
1.257     albertel 5802:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 5803: 						   'domainid');
1.324     albertel 5804:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 5805:     $r->print(<<UPLOAD);
                   5806: <script type="text/javascript" language="javascript">
                   5807:     function checkUpload(formname) {
                   5808: 	if (formname.upfile.value == "") {
                   5809: 	    alert("Please use the browse button to select a file from your local directory.");
                   5810: 	    return false;
                   5811: 	}
                   5812: 	formname.submit();
                   5813:     }
                   5814: </script>
                   5815: 
                   5816: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 5817: $default_form_data
1.181     albertel 5818: <table>
                   5819: <tr><td>$select_link </td></tr>
                   5820: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   5821: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   5822: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   5823: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   5824: </table>
1.157     albertel 5825: <input name='command' value='scantronupload_save' type='hidden' />
                   5826: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   5827: </form>
                   5828: UPLOAD
                   5829:     return '';
                   5830: }
                   5831: 
                   5832: sub scantron_upload_scantron_data_save {
                   5833:     my($r)=@_;
1.324     albertel 5834:     my ($symb)=&get_symb($r,1);
1.182     albertel 5835:     my $doanotherupload=
                   5836: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   5837: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   5838: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   5839: 	'</form>'."\n";
1.257     albertel 5840:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 5841: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 5842: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 5843: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 5844: 	if ($symb) {
1.324     albertel 5845: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 5846: 	} else {
                   5847: 	    $r->print($doanotherupload);
                   5848: 	}
1.162     albertel 5849: 	return '';
                   5850:     }
1.257     albertel 5851:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       5852:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 5853:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 5854:     #FIXME
                   5855:     #copied from lonnet::userfileupload()
                   5856:     #make that function able to target a specified course
                   5857:     # Replace Windows backslashes by forward slashes
                   5858:     $fname=~s/\\/\//g;
                   5859:     # Get rid of everything but the actual filename
                   5860:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   5861:     # Replace spaces by underscores
                   5862:     $fname=~s/\s+/\_/g;
                   5863:     # Replace all other weird characters by nothing
                   5864:     $fname=~s/[^\w\.\-]//g;
                   5865:     # See if there is anything left
                   5866:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       5867:     my $uploadedfile=$fname;
1.157     albertel 5868:     $fname='scantron_orig_'.$fname;
1.257     albertel 5869:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 5870: 	$r->print("<span class=\"LC_error\">Error:</span> 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 5871:     } else {
1.275     albertel 5872: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 5873: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 5874: 	    $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
1.210     albertel 5875: 	} else {
1.398     albertel 5876: 	    $r->print("<span class=\"LC_error\">Error:</span> An error (".$result.") occurred when attempting to upload the file, <tt>".&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</tt>");
1.183     albertel 5877: 	}
                   5878:     }
1.174     albertel 5879:     if ($symb) {
1.209     ng       5880: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 5881:     } else {
1.182     albertel 5882: 	$r->print($doanotherupload);
1.174     albertel 5883:     }
1.157     albertel 5884:     return '';
                   5885: }
                   5886: 
1.202     albertel 5887: sub valid_file {
                   5888:     my ($requested_file)=@_;
                   5889:     foreach my $filename (sort(&scantron_filenames())) {
                   5890: 	if ($requested_file eq $filename) { return 1; }
                   5891:     }
                   5892:     return 0;
                   5893: }
                   5894: 
                   5895: sub scantron_download_scantron_data {
                   5896:     my ($r)=@_;
1.324     albertel 5897:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5898:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5899:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5900:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 5901:     if (! &valid_file($file)) {
                   5902: 	$r->print(<<ERROR);
                   5903: 	<p>
                   5904: 	    The requested file name was invalid.
                   5905:         </p>
                   5906: ERROR
1.324     albertel 5907: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 5908: 	return;
                   5909:     }
                   5910:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   5911:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   5912:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   5913:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   5914:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   5915:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   5916:     $r->print(<<DOWNLOAD);
                   5917:     <p>
                   5918: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   5919:     </p>
                   5920:     <p>
                   5921: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   5922:     </p>
                   5923:     <p>
                   5924: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   5925:     </p>
                   5926: DOWNLOAD
1.324     albertel 5927:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 5928:     return '';
                   5929: }
1.157     albertel 5930: 
1.75      albertel 5931: #-------- end of section for handling grading scantron forms -------
                   5932: #
                   5933: #-------------------------------------------------------------------
                   5934: 
1.72      ng       5935: #-------------------------- Menu interface -------------------------
                   5936: #
                   5937: #--- Show a Grading Menu button - Calls the next routine ---
                   5938: sub show_grading_menu_form {
1.324     albertel 5939:     my ($symb)=@_;
1.125     ng       5940:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.72      ng       5941: 	'<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
1.257     albertel 5942: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       5943: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   5944: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   5945: 	'</form>'."\n";
                   5946:     return $result;
                   5947: }
                   5948: 
1.77      ng       5949: # -- Retrieve choices for grading form
                   5950: sub savedState {
                   5951:     my %savedState = ();
1.257     albertel 5952:     if ($env{'form.saveState'}) {
                   5953: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       5954: 	    my ($key,$value) = split(/=/,$_,2);
                   5955: 	    $savedState{$key} = $value;
                   5956: 	}
                   5957:     }
                   5958:     return \%savedState;
                   5959: }
1.76      ng       5960: 
1.72      ng       5961: #--- Displays the main menu page -------
                   5962: sub gradingmenu {
                   5963:     my ($request) = @_;
1.324     albertel 5964:     my ($symb)=&get_symb($request);
1.72      ng       5965:     if (!$symb) {return '';}
1.76      ng       5966:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       5967: 
                   5968:     $request->print(<<GRADINGMENUJS);
                   5969: <script type="text/javascript" language="javascript">
1.116     ng       5970:     function checkChoice(formname,val,cmdx) {
                   5971: 	if (val <= 2) {
                   5972: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       5973: 	    var cmdsave = cmd;
1.116     ng       5974: 	} else {
                   5975: 	    cmd = cmdx;
1.118     ng       5976: 	    cmdsave = 'submission';
1.116     ng       5977: 	}
                   5978: 	formname.command.value = cmd;
1.118     ng       5979: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 5980: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       5981: 	if (val < 5) formname.submit();
                   5982: 	if (val == 5) {
1.72      ng       5983: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   5984: 	    formname.submit();
                   5985: 	}
1.238     albertel 5986: 	if (val < 7) formname.submit();
1.72      ng       5987:     }
                   5988: 
                   5989:     function checkReceiptNo(formname,nospace) {
                   5990: 	var receiptNo = formname.receipt.value;
                   5991: 	var checkOpt = false;
                   5992: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   5993: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   5994: 	if (checkOpt) {
                   5995: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   5996: 	    formname.receipt.value = "";
                   5997: 	    formname.receipt.focus();
                   5998: 	    return false;
                   5999: 	}
                   6000: 	return true;
                   6001:     }
                   6002: </script>
                   6003: GRADINGMENUJS
1.118     ng       6004:     &commonJSfunctions($request);
1.398     albertel 6005:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
1.324     albertel 6006:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       6007:     $result.=$table;
1.76      ng       6008:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       6009:     my $savedState = &savedState();
1.118     ng       6010:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       6011:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       6012:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       6013:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       6014: 
                   6015:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   6016: 	'<input type="hidden" name="symb"        value="'.$symb.'" />'."\n".
                   6017: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   6018: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       6019: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       6020: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       6021: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       6022: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   6023: 
1.326     albertel 6024:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   6025: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
1.72      ng       6026: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       6027: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   6028: 
1.326     albertel 6029:     $result.='<table width="100%" border="0">';
1.116     ng       6030:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.167     sakharuk 6031: 	'&nbsp;'.&mt('Select Section').': <select name="section">'."\n";
1.116     ng       6032:     if (ref($sections)) {
1.155     albertel 6033: 	foreach (sort (@$sections)) {
                   6034: 	    $result.='<option value="'.$_.'" '.
1.401     albertel 6035: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
1.155     albertel 6036: 	}
1.116     ng       6037:     }
1.401     albertel 6038:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.116     ng       6039: 
1.401     albertel 6040:     $result.=&mt('Student Status').':'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
1.72      ng       6041: 
1.116     ng       6042:     $result.='</td></tr>';
                   6043: 
1.288     albertel 6044:     $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
1.118     ng       6045: 	'<input type="radio" name="radioChoice" value="submission" '.
1.401     albertel 6046: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 6047: 	'</label> <select name="submitonly">'.
1.145     albertel 6048: 	'<option value="yes" '.
1.401     albertel 6049: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
1.301     albertel 6050: 	'<option value="queued" '.
1.401     albertel 6051: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
1.145     albertel 6052: 	'<option value="graded" '.
1.401     albertel 6053: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 6054: 	'<option value="incorrect" '.
1.401     albertel 6055: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 6056: 	'<option value="all" '.
1.401     albertel 6057: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       6058: 
1.116     ng       6059:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.288     albertel 6060: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.401     albertel 6061: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
1.288     albertel 6062: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       6063: 
1.118     ng       6064:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
1.288     albertel 6065: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.401     albertel 6066: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
1.288     albertel 6067: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       6068: 
1.116     ng       6069:     $result.='<tr bgcolor="#ffffe6"><td><br />'.
1.126     ng       6070: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       6071: 	'</td></tr></table>'."\n";
                   6072: 
                   6073:     $result.='</td><td valign="top">';
                   6074: 
1.326     albertel 6075:     $result.='<table width="100%" border="0">';
1.116     ng       6076:     $result.='<tr bgcolor="#ffffe6"><td>'.
1.184     www      6077: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   6078: 	' '.&mt('scores from file').' </td></tr>'."\n";
1.72      ng       6079: 
1.404     www      6080:     $result.='<tr bgcolor="#ffffe6"><td>'.
                   6081:         '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
                   6082:         ' '.&mt('clicker file').' </td></tr>'."\n";
1.400     www      6083: 
1.75      albertel 6084:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.116     ng       6085: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
1.184     www      6086: 	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
1.75      albertel 6087: 
1.257     albertel 6088:     if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
1.72      ng       6089: 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.184     www      6090: 	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   6091: 	    ' '.&mt('receipt').': '.
1.257     albertel 6092: 	    &Apache::lonnet::recprefix($env{'request.course.id'}).
1.326     albertel 6093: 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
1.72      ng       6094: 	    '</td></tr>'."\n";
                   6095:     } 
1.238     albertel 6096:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   6097: 	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   6098: 	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
1.279     albertel 6099:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   6100: 	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   6101: 	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
1.44      ng       6102: 
1.401     albertel 6103:     $result.='</table>'."\n".
1.72      ng       6104: 	'</td></tr></table>'."\n".
1.401     albertel 6105: 	'</td></tr></table></form>'."\n";
1.44      ng       6106:     return $result;
1.2       albertel 6107: }
                   6108: 
1.285     albertel 6109: sub reset_perm {
                   6110:     undef(%perm);
                   6111: }
                   6112: 
                   6113: sub init_perm {
                   6114:     &reset_perm();
1.300     albertel 6115:     foreach my $test_perm ('vgr','mgr','opa') {
                   6116: 
                   6117: 	my $scope = $env{'request.course.id'};
                   6118: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   6119: 
                   6120: 	    $scope .= '/'.$env{'request.course.sec'};
                   6121: 	    if ( $perm{$test_perm}=
                   6122: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   6123: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   6124: 	    } else {
                   6125: 		delete($perm{$test_perm});
                   6126: 	    }
1.285     albertel 6127: 	}
                   6128:     }
                   6129: }
                   6130: 
1.400     www      6131: sub gather_clicker_ids {
1.408     albertel 6132:     my %clicker_ids;
1.400     www      6133: 
                   6134:     my $classlist = &Apache::loncoursedata::get_classlist();
                   6135: 
                   6136:     # Set up a couple variables.
1.407     albertel 6137:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   6138:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.400     www      6139: 
1.407     albertel 6140:     foreach my $student (keys(%$classlist)) {
1.400     www      6141: 
1.407     albertel 6142:         my $username = $classlist->{$student}->[$username_idx];
                   6143:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      6144:         my $clickers =
1.408     albertel 6145: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      6146:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      6147:             $id=~s/^[\#0]+//;
1.407     albertel 6148:             if (exists($clicker_ids{$id})) {
1.408     albertel 6149: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      6150:             } else {
1.408     albertel 6151: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      6152:             }
                   6153:         }
                   6154:     }
1.407     albertel 6155:     return %clicker_ids;
1.400     www      6156: }
                   6157: 
1.402     www      6158: sub gather_adv_clicker_ids {
1.408     albertel 6159:     my %clicker_ids;
1.402     www      6160:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6161:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6162:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 6163:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      6164:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   6165:             my ($puname,$pudom)=split(/\:/,$person);
                   6166:             my $clickers =
1.408     albertel 6167: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      6168:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      6169: 		$id=~s/^[\#0]+//;
1.408     albertel 6170: 		if (exists($clicker_ids{$id})) {
                   6171: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   6172: 		} else {
                   6173: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   6174: 		}
1.405     www      6175:             }
1.402     www      6176:         }
                   6177:     }
1.407     albertel 6178:     return %clicker_ids;
1.402     www      6179: }
                   6180: 
1.413     www      6181: sub clicker_grading_parameters {
                   6182:     return ('gradingmechanism' => 'scalar',
                   6183:             'upfiletype' => 'scalar',
                   6184:             'specificid' => 'scalar',
                   6185:             'pcorrect' => 'scalar',
                   6186:             'pincorrect' => 'scalar');
                   6187: }
                   6188: 
1.400     www      6189: sub process_clicker {
                   6190:     my ($r)=@_;
                   6191:     my ($symb)=&get_symb($r);
                   6192:     if (!$symb) {return '';}
                   6193:     my $result=&checkforfile_js();
                   6194:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   6195:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   6196:     $result.=$table;
                   6197:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   6198:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   6199:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   6200:         '.</b></td></tr>'."\n";
                   6201:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      6202: # Attempt to restore parameters from last session, set defaults if not present
                   6203:     my %Saveable_Parameters=&clicker_grading_parameters();
                   6204:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   6205:                                                  \%Saveable_Parameters);
                   6206:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   6207:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   6208:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   6209:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   6210: 
                   6211:     my %checked;
                   6212:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   6213:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   6214:           $checked{$gradingmechanism}="checked='checked'";
                   6215:        }
                   6216:     }
                   6217: 
1.400     www      6218:     my $upload=&mt("Upload File");
                   6219:     my $type=&mt("Type");
1.402     www      6220:     my $attendance=&mt("Award points just for participation");
                   6221:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      6222:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      6223:     my $pcorrect=&mt("Percentage points for correct solution");
                   6224:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      6225:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.408     albertel 6226: 						   ('iclicker' => 'i>clicker'));
1.400     www      6227: 
                   6228:     $result.=<<ENDUPFORM;
1.402     www      6229: <script type="text/javascript">
                   6230: function sanitycheck() {
                   6231: // Accept only integer percentages
                   6232:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   6233:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   6234: // Find out grading choice
                   6235:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   6236:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   6237:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   6238:       }
                   6239:    }
                   6240: // By default, new choice equals user selection
                   6241:    newgradingchoice=gradingchoice;
                   6242: // Not good to give more points for false answers than correct ones
                   6243:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   6244:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   6245:    }
                   6246: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   6247:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   6248:       document.forms.gradesupload.pcorrect.value=100;
                   6249:       document.forms.gradesupload.pincorrect.value=100;
                   6250:    }
                   6251: // If the values are different, cannot be attendance only
                   6252:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   6253:        (gradingchoice=='attendance')) {
                   6254:        newgradingchoice='personnel';
                   6255:    }
                   6256: // Change grading choice to new one
                   6257:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   6258:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   6259:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   6260:       } else {
                   6261:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   6262:       }
                   6263:    }
                   6264: // Remember the old state
                   6265:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   6266: }
                   6267: </script>
1.400     www      6268: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   6269: <input type="hidden" name="symb" value="$symb" />
                   6270: <input type="hidden" name="command" value="processclickerfile" />
                   6271: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   6272: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   6273: <input type="file" name="upfile" size="50" />
                   6274: <br /><label>$type: $selectform</label>
1.413     www      6275: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
                   6276: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
                   6277: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
1.414     www      6278: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      6279: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   6280: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   6281: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      6282: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   6283: </form>
                   6284: ENDUPFORM
                   6285:     $result.='</td></tr></table>'."\n".
                   6286:              '</td></tr></table><br /><br />'."\n";
                   6287:     $result.=&show_grading_menu_form($symb);
                   6288:     return $result;
                   6289: }
                   6290: 
                   6291: sub process_clicker_file {
                   6292:     my ($r)=@_;
                   6293:     my ($symb)=&get_symb($r);
                   6294:     if (!$symb) {return '';}
1.413     www      6295: 
                   6296:     my %Saveable_Parameters=&clicker_grading_parameters();
                   6297:     &Apache::loncommon::store_course_settings('grades_clicker',
                   6298:                                               \%Saveable_Parameters);
                   6299: 
1.400     www      6300:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      6301:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 6302: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   6303: 	return $result.&show_grading_menu_form($symb);
1.404     www      6304:     }
1.407     albertel 6305:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 6306:     my %correct_ids;
1.404     www      6307:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 6308: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      6309:     }
                   6310:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      6311: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   6312: 	   $correct_id=~tr/a-z/A-Z/;
                   6313: 	   $correct_id=~s/\s//gs;
                   6314: 	   $correct_id=~s/^[\#0]+//;
                   6315:            if ($correct_id) {
                   6316: 	      $correct_ids{$correct_id}='specified';
                   6317:            }
                   6318:         }
1.400     www      6319:     }
1.404     www      6320:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 6321: 	$result.=&mt('Score based on attendance only');
1.404     www      6322:     } else {
1.408     albertel 6323: 	my $number=0;
1.411     www      6324: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 6325: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      6326: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 6327: 	    if ($correct_ids{$id} eq 'specified') {
                   6328: 		$result.=&mt('specified');
                   6329: 	    } else {
                   6330: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   6331: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   6332: 	    }
                   6333: 	    $number++;
                   6334: 	}
1.411     www      6335:         $result.="</p>\n";
1.408     albertel 6336: 	if ($number==0) {
                   6337: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   6338: 	    return $result.&show_grading_menu_form($symb);
                   6339: 	}
1.404     www      6340:     }
1.405     www      6341:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 6342:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   6343: 		     '<span class="LC_error">',
                   6344: 		     '</span>',
                   6345: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      6346:         return $result.&show_grading_menu_form($symb);
                   6347:     }
1.410     www      6348: 
                   6349: # Were able to get all the info needed, now analyze the file
                   6350: 
1.411     www      6351:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.410     www      6352:     my $heading=&mt('Scanning clicker file');
                   6353:     $result.=(<<ENDHEADER);
                   6354: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   6355: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   6356: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   6357: <form method="post" action="/adm/grades" name="clickeranalysis">
                   6358: <input type="hidden" name="symb" value="$symb" />
                   6359: <input type="hidden" name="command" value="assignclickergrades" />
                   6360: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   6361: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      6362: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   6363: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   6364: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      6365: ENDHEADER
1.408     albertel 6366:     my %responses;
                   6367:     my @questiontitles;
1.405     www      6368:     my $errormsg='';
                   6369:     my $number=0;
                   6370:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 6371: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      6372:     }
1.411     www      6373:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   6374:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   6375:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   6376:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   6377:              '<br />';
1.414     www      6378: # Remember Question Titles
                   6379: # FIXME: Possibly need delimiter other than ":"
                   6380:     for (my $i=0;$i<$number;$i++) {
                   6381:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   6382:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   6383:     }
1.411     www      6384:     my $correct_count=0;
                   6385:     my $student_count=0;
                   6386:     my $unknown_count=0;
1.414     www      6387: # Match answers with usernames
                   6388: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 6389:     foreach my $id (keys(%responses)) {
1.410     www      6390:        if ($correct_ids{$id}) {
1.414     www      6391:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      6392:           $correct_count++;
1.410     www      6393:        } elsif ($clicker_ids{$id}) {
                   6394:           $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      6395:           $student_count++;
1.410     www      6396:        } else {
1.411     www      6397:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   6398:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   6399:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   6400:                    "\n".&mt("Domain").": ".
                   6401:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   6402:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   6403:           $unknown_count++;
1.410     www      6404:        }
1.405     www      6405:     }
1.412     www      6406:     $result.='<hr />'.
                   6407:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   6408:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   6409:        if ($correct_count==0) {
                   6410:           $errormsg.="Found no correct answers answers for grading!";
                   6411:        } elsif ($correct_count>1) {
1.414     www      6412:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      6413:        }
                   6414:     }
                   6415:     if ($errormsg) {
                   6416:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   6417:     } else {
                   6418:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   6419:     }
                   6420:     $result.='</form></td></tr></table>'."\n".
1.410     www      6421:              '</td></tr></table><br /><br />'."\n";
1.404     www      6422:     return $result.&show_grading_menu_form($symb);
1.400     www      6423: }
                   6424: 
1.405     www      6425: sub iclicker_eval {
1.406     www      6426:     my ($questiontitles,$responses)=@_;
1.405     www      6427:     my $number=0;
                   6428:     my $errormsg='';
                   6429:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      6430:         my %components=&Apache::loncommon::record_sep($line);
                   6431:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 6432: 	if ($entries[0] eq 'Question') {
                   6433: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   6434: 		$$questiontitles[$number]=$entries[$i];
                   6435: 		$number++;
                   6436: 	    }
                   6437: 	}
                   6438: 	if ($entries[0]=~/^\#/) {
                   6439: 	    my $id=$entries[0];
                   6440: 	    my @idresponses;
                   6441: 	    $id=~s/^[\#0]+//;
                   6442: 	    for (my $i=0;$i<$number;$i++) {
                   6443: 		my $idx=3+$i*6;
                   6444: 		push(@idresponses,$entries[$idx]);
                   6445: 	    }
                   6446: 	    $$responses{$id}=join(',',@idresponses);
                   6447: 	}
1.405     www      6448:     }
                   6449:     return ($errormsg,$number);
                   6450: }
                   6451: 
1.414     www      6452: sub assign_clicker_grades {
                   6453:     my ($r)=@_;
                   6454:     my ($symb)=&get_symb($r);
                   6455:     if (!$symb) {return '';}
1.416   ! www      6456: # See which part we are saving to
        !          6457:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
        !          6458: # FIXME: This should probably look for the first handgradeable part
        !          6459:     my $part=$$partlist[0];
        !          6460: # Start screen output
1.414     www      6461:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416   ! www      6462: 
1.414     www      6463:     my $heading=&mt('Assigning grades based on clicker file');
                   6464:     $result.=(<<ENDHEADER);
                   6465: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   6466: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   6467: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   6468: ENDHEADER
                   6469: # Get correct result
                   6470: # FIXME: Possibly need delimiter other than ":"
                   6471:     my @correct=();
1.415     www      6472:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   6473:     my $number=$env{'form.number'};
                   6474:     if ($gradingmechanism ne 'attendance') {
1.414     www      6475:        foreach my $key (keys(%env)) {
                   6476:           if ($key=~/^form\.correct\:/) {
                   6477:              my @input=split(/\,/,$env{$key});
                   6478:              for (my $i=0;$i<=$#input;$i++) {
                   6479:                  if (($correct[$i]) && ($input[$i]) &&
                   6480:                      ($correct[$i] ne $input[$i])) {
                   6481:                     $result.='<br /><span class="LC_warning">'.
                   6482:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   6483:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   6484:                  } elsif ($input[$i]) {
                   6485:                     $correct[$i]=$input[$i];
                   6486:                  }
                   6487:              }
                   6488:           }
                   6489:        }
1.415     www      6490:        for (my $i=0;$i<$number;$i++) {
1.414     www      6491:           if (!$correct[$i]) {
                   6492:              $result.='<br /><span class="LC_error">'.
                   6493:                       &mt('No correct result given for question "[_1]"!',
                   6494:                           $env{'form.question:'.$i}).'</span>';
                   6495:           }
                   6496:        }
                   6497:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   6498:     }
                   6499: # Start grading
1.415     www      6500:     my $pcorrect=$env{'form.pcorrect'};
                   6501:     my $pincorrect=$env{'form.pincorrect'};
1.416   ! www      6502:     my $storecount=0;
1.415     www      6503:     foreach my $key (keys(%env)) {
                   6504:        if ($key=~/^form\.student\:(.*)$/) {
                   6505:           my $user=$1;
                   6506:           my @answer=split(/\,/,$env{$key});
                   6507:           my $sum=0;
                   6508:           for (my $i=0;$i<$number;$i++) {
                   6509:              if ($answer[$i]) {
                   6510:                 if ($gradingmechanism eq 'attendance') {
                   6511:                    $sum+=$pcorrect;
                   6512:                 } else {
                   6513:                    if ($answer[$i] eq $correct[$i]) {
                   6514:                       $sum+=$pcorrect;
                   6515:                    } else {
                   6516:                       $sum+=$pincorrect;
                   6517:                    }
                   6518:                 }
                   6519:              }
                   6520:           }
1.416   ! www      6521:           my $ave=$sum/(100*$number);
        !          6522: # Store
        !          6523:           my ($username,$domain)=split(/\:/,$user);
        !          6524:           my %grades=();
        !          6525:           $grades{"resource.$part.solved"}='correct_by_override';
        !          6526:           $grades{"resource.$part.awarded"}=$ave;
        !          6527:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
        !          6528:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
        !          6529:                                                  $env{'request.course.id'},
        !          6530:                                                  $domain,$username);
        !          6531:           if ($returncode ne 'ok') {
        !          6532:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
        !          6533:           } else {
        !          6534:              $storecount++;
        !          6535:           }
1.415     www      6536:        }
                   6537:     }
                   6538: # We are done
1.416   ! www      6539:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
        !          6540:              '</td></tr></table>'."\n".
1.414     www      6541:              '</td></tr></table><br /><br />'."\n";
                   6542:     return $result.&show_grading_menu_form($symb);
                   6543: }
                   6544: 
1.1       albertel 6545: sub handler {
1.41      ng       6546:     my $request=$_[0];
1.102     albertel 6547: 
1.285     albertel 6548:     &reset_perm();
1.257     albertel 6549:     if ($env{'browser.mathml'}) {
1.141     www      6550: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       6551:     } else {
1.141     www      6552: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       6553:     }
                   6554:     $request->send_http_header;
1.44      ng       6555:     return '' if $request->header_only;
1.41      ng       6556:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 6557:     my $symb=&get_symb($request,1);
1.160     albertel 6558:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   6559:     my $command=$commands[0];
                   6560:     if ($#commands > 0) {
                   6561: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   6562:     }
1.353     albertel 6563:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 6564:     if ($symb eq '' && $command eq '') {
1.257     albertel 6565: 	if ($env{'user.adv'}) {
                   6566: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   6567: 		($env{'form.codethree'})) {
                   6568: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   6569: 		    $env{'form.codethree'};
1.41      ng       6570: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   6571: 		    &Apache::lonnet::checkin($token);
                   6572: 		if ($tsymb) {
1.137     albertel 6573: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       6574: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 6575: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   6576: 					  ('grade_username' => $tuname,
                   6577: 					   'grade_domain' => $tudom,
                   6578: 					   'grade_courseid' => $tcrsid,
                   6579: 					   'grade_symb' => $tsymb)));
1.41      ng       6580: 		    } else {
1.45      ng       6581: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 6582: 		    }
1.41      ng       6583: 		} else {
1.45      ng       6584: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       6585: 		}
1.14      www      6586: 	    } else {
1.41      ng       6587: 		$request->print(&Apache::lonxml::tokeninputfield());
                   6588: 	    }
                   6589: 	}
                   6590:     } else {
1.285     albertel 6591: 	&init_perm();
1.104     albertel 6592: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 6593: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 6594: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       6595: 	    &pickStudentPage($request);
1.103     albertel 6596: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       6597: 	    &displayPage($request);
1.104     albertel 6598: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       6599: 	    &updateGradeByPage($request);
1.104     albertel 6600: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       6601: 	    &processGroup($request);
1.104     albertel 6602: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.41      ng       6603: 	    $request->print(&gradingmenu($request));
1.104     albertel 6604: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       6605: 	    $request->print(&viewgrades($request));
1.104     albertel 6606: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       6607: 	    $request->print(&processHandGrade($request));
1.106     albertel 6608: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       6609: 	    $request->print(&editgrades($request));
1.106     albertel 6610: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       6611: 	    $request->print(&verifyreceipt($request));
1.400     www      6612:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   6613:             $request->print(&process_clicker($request));
                   6614:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   6615:             $request->print(&process_clicker_file($request));
1.414     www      6616:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   6617:             $request->print(&assign_clicker_grades($request));
1.106     albertel 6618: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       6619: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 6620: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       6621: 	    $request->print(&csvupload($request));
1.106     albertel 6622: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       6623: 	    $request->print(&csvuploadmap($request));
1.246     albertel 6624: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 6625: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 6626: 		$request->print(&csvuploadoptions($request));
1.41      ng       6627: 	    } else {
1.257     albertel 6628: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   6629: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       6630: 		} else {
1.257     albertel 6631: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       6632: 		}
                   6633: 		$request->print(&csvuploadmap($request));
                   6634: 	    }
1.246     albertel 6635: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   6636: 	    $request->print(&csvuploadassign($request));
1.106     albertel 6637: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 6638: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 6639:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   6640:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 6641: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   6642: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 6643: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 6644: 	    $request->print(&scantron_process_students($request));
1.157     albertel 6645:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 6646:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   6647: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 6648:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 6649:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 6650:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   6651: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 6652:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 6653:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 6654: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 6655:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 6656: 	} elsif ($command) {
1.157     albertel 6657: 	    $request->print("Access Denied ($command)");
1.26      albertel 6658: 	}
1.2       albertel 6659:     }
1.353     albertel 6660:     $request->print(&Apache::loncommon::end_page());
1.44      ng       6661:     return '';
                   6662: }
                   6663: 
1.1       albertel 6664: 1;
                   6665: 
1.13      albertel 6666: __END__;

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