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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.431   ! banghart    4: # $Id: grades.pm,v 1.430 2007/08/21 18:41:27 banghart Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: package Apache::grades;
                     30: use strict;
                     31: use Apache::style;
                     32: use Apache::lonxml;
                     33: use Apache::lonnet;
1.3       albertel   34: use Apache::loncommon;
1.112     ng         35: use Apache::lonhtmlcommon;
1.68      ng         36: use Apache::lonnavmaps;
1.1       albertel   37: use Apache::lonhomework;
1.55      matthew    38: use Apache::loncoursedata;
1.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: 
1.103     albertel   48: my %perm=();
1.1       albertel   49: 
1.68      ng         50: # ----- These first few routines are general use routines.----
1.44      ng         51: #
1.146     albertel   52: # --- Retrieve the parts from the metadata file.---
1.44      ng         53: sub getpartlist {
1.324     albertel   54:     my ($symb) = @_;
                     55:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.146     albertel   56:     my $partorder = &Apache::lonnet::metadata($url, 'partorder');
                     57:     my @parts;
                     58:     if ($partorder) {
                     59: 	for my $part (split (/,/,$partorder)) {
                     60: 	    if (!&Apache::loncommon::check_if_partid_hidden($part,$symb)) {
                     61: 		push(@parts, $part);
                     62: 	    }
                     63: 	}	    
                     64:     } else {
                     65: 	my $metadata = &Apache::lonnet::metadata($url, 'packages');
                     66: 	foreach (split(/\,/,$metadata)) {
                     67: 	    if ($_ =~ /^part_(.*)$/) {
                     68: 		if (!&Apache::loncommon::check_if_partid_hidden($1,$symb)) {
                     69: 		    push(@parts, $1);
                     70: 		}
                     71: 	    }
1.41      ng         72: 	}
1.16      albertel   73:     }
1.146     albertel   74:     my @stores;
                     75:     foreach my $part (@parts) {
                     76: 	my (@metakeys) = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                     77: 	foreach my $key (@metakeys) {
                     78: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                     79: 	}
                     80:     }
                     81:     return @stores;
1.2       albertel   82: }
                     83: 
1.44      ng         84: # --- Get the symbolic name of a problem and the url
1.324     albertel   85: sub get_symb {
1.173     albertel   86:     my ($request,$silent) = @_;
1.257     albertel   87:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                     88:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel   89:     if ($symb eq '') { 
                     90: 	if (!$silent) {
                     91: 	    $request->print("Unable to handle ambiguous references:$url:.");
                     92: 	    return ();
                     93: 	}
                     94:     }
1.418     albertel   95:     &Apache::lonenc::check_decrypt(\$symb);
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".
1.418     albertel  495: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($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 {
1.426     albertel  540:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       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 ...
1.426     albertel  557:     foreach my $tkey (keys(%$old_essays)) {
                    558: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       559: # ... except the same student
1.426     albertel  560:         next if (($tname eq $uname) && ($tdom eq $udom));
                    561: 	my $tessay=$old_essays->{$tkey};
                    562: 	$tessay=~s/\W+/ /gs;
1.87      www       563: # String similarity gives up if not even limit
1.426     albertel  564: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       565: # Found one
1.426     albertel  566: 	if ($tsimilar>$limit) {
                    567: 	    $limit=$tsimilar;
                    568: 	    $sname=$tname;
                    569: 	    $sdom=$tdom;
                    570: 	    $scrsid=$tcrsid;
                    571: 	    $sessay=$old_essays->{$tkey};
                    572: 	}
1.87      www       573:     }
1.88      www       574:     if ($limit>0.6) {
1.87      www       575:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    576:     } else {
                    577:        return ('','','','',0);
                    578:     }
                    579: }
                    580: 
1.44      ng        581: #-------------------------------------------------------------------
                    582: 
                    583: #------------------------------------ Receipt Verification Routines
1.45      ng        584: #
1.44      ng        585: #--- Check whether a receipt number is valid.---
                    586: sub verifyreceipt {
                    587:     my $request  = shift;
                    588: 
1.257     albertel  589:     my $courseid = $env{'request.course.id'};
1.184     www       590:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  591: 	$env{'form.receipt'};
1.44      ng        592:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  593:     my ($symb)   = &get_symb($request);
1.44      ng        594: 
1.398     albertel  595:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
                    596: 	$receipt.'</h3></span>'."\n".
                    597: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
1.44      ng        598: 
                    599:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   600:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  601:     
                    602:     my $receiptparts=0;
1.390     albertel  603:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    604: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  605:     my $parts=['0'];
1.324     albertel  606:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.294     albertel  607:     foreach (sort 
                    608: 	     {
                    609: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    610: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    611: 		 }
                    612: 		 return $a cmp $b;
                    613: 	     } (keys(%$fullname))) {
1.44      ng        614: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  615: 	foreach my $part (@$parts) {
                    616: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
                    617: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
                    618: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  619: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  620: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    621: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    622: 		if ($receiptparts) {
                    623: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    624: 		}
                    625: 		$contents.='</tr>'."\n";
                    626: 		
                    627: 		$matches++;
                    628: 	    }
1.44      ng        629: 	}
                    630:     }
                    631:     if ($matches == 0) {
                    632: 	$string = $title.'No match found for the above receipt.';
                    633:     } else {
1.324     albertel  634: 	$string = &jscriptNform($symb).$title.
1.44      ng        635: 	    'The above receipt matches the following student'.
                    636: 	    ($matches <= 1 ? '.' : 's.')."\n".
                    637: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                    638: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
                    639: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
                    640: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
1.177     albertel  641: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
                    642: 	if ($receiptparts) {
                    643: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
                    644: 	}
                    645: 	$string.='</tr>'."\n".$contents.
1.44      ng        646: 	    '</table></td></tr></table>'."\n";
                    647:     }
1.324     albertel  648:     return $string.&show_grading_menu_form($symb);
1.44      ng        649: }
                    650: 
                    651: #--- This is called by a number of programs.
                    652: #--- Called from the Grading Menu - View/Grade an individual student
                    653: #--- Also called directly when one clicks on the subm button 
                    654: #    on the problem page.
1.30      ng        655: sub listStudents {
1.41      ng        656:     my ($request) = shift;
1.49      albertel  657: 
1.324     albertel  658:     my ($symb) = &get_symb($request);
1.257     albertel  659:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    660:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    661:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                    662:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    663: 
                    664:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    665:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    666: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  667: 
1.398     albertel  668:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
                    669: 	' Submissions for a Student or a Group of Students</span></h3>';
1.118     ng        670: 
1.324     albertel  671:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  672: 
1.45      ng        673:     $request->print(<<LISTJAVASCRIPT);
                    674: <script type="text/javascript" language="javascript">
1.110     ng        675:     function checkSelect(checkBox) {
                    676: 	var ctr=0;
                    677: 	var sense="";
                    678: 	if (checkBox.length > 1) {
                    679: 	    for (var i=0; i<checkBox.length; i++) {
                    680: 		if (checkBox[i].checked) {
                    681: 		    ctr++;
                    682: 		}
                    683: 	    }
                    684: 	    sense = "a student or group of students";
                    685: 	} else {
                    686: 	    if (checkBox.checked) {
                    687: 		ctr = 1;
                    688: 	    }
                    689: 	    sense = "the student";
                    690: 	}
                    691: 	if (ctr == 0) {
1.126     ng        692: 	    alert("Please select "+sense+" before clicking on the Next button.");
1.110     ng        693: 	    return false;
                    694: 	}
                    695: 	document.gradesub.submit();
                    696:     }
                    697: 
                    698:     function reLoadList(formname) {
1.112     ng        699: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        700: 	formname.command.value = 'submission';
                    701: 	formname.submit();
                    702:     }
1.45      ng        703: </script>
                    704: LISTJAVASCRIPT
                    705: 
1.118     ng        706:     &commonJSfunctions($request);
1.41      ng        707:     $request->print($result);
1.39      ng        708: 
1.401     albertel  709:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    710:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  711:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
                    712: 	"\n".$table.
1.401     albertel  713: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.267     albertel  714: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
                    715: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
                    716: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
                    717: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
1.401     albertel  718: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
1.49      albertel  719: 	'&nbsp;<b>Submissions: </b>'."\n";
1.257     albertel  720:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.267     albertel  721: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
1.49      albertel  722:     }
1.110     ng        723: 
1.257     albertel  724:     my $saveStatus = $env{'form.Status'} eq '' ? 'Active' : $env{'form.Status'};
                    725:     $env{'form.Status'} = $saveStatus;
1.110     ng        726: 
1.267     albertel  727:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
                    728: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
                    729: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
1.348     bowersj2  730: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
                    731:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
                    732:         '<option value="1">Whole Points</option>'.
                    733:         '<option value=".5">Half Points</option>'.
1.349     albertel  734:         '<option value=".25">Quarter Points</option>'.
                    735:         '<option value=".1">Tenths of a Point</option>'.
1.348     bowersj2  736:         '</select>'.
                    737: 
1.45      ng        738: 	'<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
                    739: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  740: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    741: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    742: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    743: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  744: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        745: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    746: 
1.257     albertel  747:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
                    748: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng        749:     } else {
                    750: 	$gradeTable.='<b>Student Status:</b> '.
                    751: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
                    752:     }
1.112     ng        753: 
1.126     ng        754:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    755: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
1.110     ng        756: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  757: 
                    758: # checkall buttons
                    759:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        760:     $gradeTable.='<input type="button" '."\n".
1.45      ng        761: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.249     albertel  762: 	'value="Next->" /> <br />'."\n";
                    763:     $gradeTable.=&check_buttons();
1.401     albertel  764:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
1.249     albertel  765:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
1.45      ng        766:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
1.110     ng        767: 	'<table border="0"><tr bgcolor="#e6ffff">';
                    768:     my $loop = 0;
                    769:     while ($loop < 2) {
1.126     ng        770: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
1.250     albertel  771: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
1.301     albertel  772: 	if ($env{'form.showgrading'} eq 'yes' 
                    773: 	    && $submitonly ne 'queued'
                    774: 	    && $submitonly ne 'all') {
1.110     ng        775: 	    foreach (sort(@$partlist)) {
1.324     albertel  776: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
1.207     albertel  777: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
                    778: 		    ' Status&nbsp;</b></td>';
1.110     ng        779: 	    }
1.301     albertel  780: 	} elsif ($submitonly eq 'queued') {
                    781: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
1.110     ng        782: 	}
                    783: 	$loop++;
1.126     ng        784: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        785:     }
1.45      ng        786:     $gradeTable.='</tr>'."\n";
1.41      ng        787: 
1.45      ng        788:     my $ctr = 0;
1.294     albertel  789:     foreach my $student (sort 
                    790: 			 {
                    791: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    792: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    793: 			     }
                    794: 			     return $a cmp $b;
                    795: 			 }
                    796: 			 (keys(%$fullname))) {
1.41      ng        797: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  798: 
1.110     ng        799: 	my %status = ();
1.301     albertel  800: 
                    801: 	if ($submitonly eq 'queued') {
                    802: 	    my %queue_status = 
                    803: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    804: 							$udom,$uname);
                    805: 	    next if (!defined($queue_status{'gradingqueue'}));
                    806: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    807: 	}
                    808: 
                    809: 	if ($env{'form.showgrading'} eq 'yes' 
                    810: 	    && $submitonly ne 'queued'
                    811: 	    && $submitonly ne 'all') {
1.324     albertel  812: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  813: 	    my $submitted = 0;
1.164     albertel  814: 	    my $graded = 0;
1.248     albertel  815: 	    my $incorrect = 0;
1.110     ng        816: 	    foreach (keys(%status)) {
1.145     albertel  817: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  818: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    819: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    820: 		
1.110     ng        821: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    822: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  823: 		    $submitted = 0;
1.150     albertel  824: 		    my ($part)=split(/\./,$partid);
1.110     ng        825: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  826: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        827: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    828: 		}
1.41      ng        829: 	    }
1.248     albertel  830: 	    
1.156     albertel  831: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    832: 				     $submitonly eq 'incorrect' ||
                    833: 				     $submitonly eq 'graded'));
1.248     albertel  834: 	    next if (!$graded && ($submitonly eq 'graded'));
                    835: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        836: 	}
1.34      ng        837: 
1.45      ng        838: 	$ctr++;
1.249     albertel  839: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    840: 
1.104     albertel  841: 	if ( $perm{'vgr'} eq 'F' ) {
1.110     ng        842: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
1.126     ng        843: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  844:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    845:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    846: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    847: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
                    848: 	       '&nbsp;'.$section.'</td>'."\n";
1.110     ng        849: 
1.257     albertel  850: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        851: 		foreach (sort keys(%status)) {
                    852: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  853: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        854: 		}
1.41      ng        855: 	    }
1.126     ng        856: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.110     ng        857: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
1.41      ng        858: 	}
                    859:     }
1.110     ng        860:     if ($ctr%2 ==1) {
1.126     ng        861: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel  862: 	    if ($env{'form.showgrading'} eq 'yes' 
                    863: 		&& $submitonly ne 'queued'
                    864: 		&& $submitonly ne 'all') {
1.110     ng        865: 		foreach (@$partlist) {
                    866: 		    $gradeTable.='<td>&nbsp;</td>';
                    867: 		}
1.301     albertel  868: 	    } elsif ($submitonly eq 'queued') {
                    869: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng        870: 	    }
                    871: 	$gradeTable.='</tr>';
                    872:     }
                    873: 
1.249     albertel  874:     $gradeTable.='</table></td></tr></table>'."\n".
1.45      ng        875: 	'<input type="button" '.
                    876: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng        877: 	'value="Next->" /></form>'."\n";
1.45      ng        878:     if ($ctr == 0) {
1.96      albertel  879: 	my $num_students=(scalar(keys(%$fullname)));
                    880: 	if ($num_students eq 0) {
1.398     albertel  881: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel  882: 	} else {
1.171     albertel  883: 	    my $submissions='submissions';
                    884: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                    885: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel  886: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel  887: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel  888: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel  889: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel  890: 	}
1.46      ng        891:     } elsif ($ctr == 1) {
                    892: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
1.45      ng        893:     }
1.324     albertel  894:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng        895:     $request->print($gradeTable);
1.44      ng        896:     return '';
1.10      ng        897: }
                    898: 
1.44      ng        899: #---- Called from the listStudents routine
1.249     albertel  900: 
                    901: sub check_script {
                    902:     my ($form, $type)=@_;
                    903:     my $chkallscript='<script type="text/javascript">
                    904:     function checkall() {
                    905:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    906:             ele = document.forms.'.$form.'.elements[i];
                    907:             if (ele.name == "'.$type.'") {
                    908:             document.forms.'.$form.'.elements[i].checked=true;
                    909:                                        }
                    910:         }
                    911:     }
                    912: 
                    913:     function checksec() {
                    914:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    915:             ele = document.forms.'.$form.'.elements[i];
                    916:            string = document.forms.'.$form.'.chksec.value;
                    917:            if
                    918:           (ele.value.indexOf(":::SECTION"+string)>0) {
                    919:               document.forms.'.$form.'.elements[i].checked=true;
                    920:             }
                    921:         }
                    922:     }
                    923: 
                    924: 
                    925:     function uncheckall() {
                    926:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    927:             ele = document.forms.'.$form.'.elements[i];
                    928:             if (ele.name == "'.$type.'") {
                    929:             document.forms.'.$form.'.elements[i].checked=false;
                    930:                                        }
                    931:         }
                    932:     }
                    933: 
                    934: </script>'."\n";
                    935:     return $chkallscript;
                    936: }
                    937: 
                    938: sub check_buttons {
                    939:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                    940:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                    941:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                    942:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                    943:     return $buttons;
                    944: }
                    945: 
1.44      ng        946: #     Displays the submissions for one student or a group of students
1.34      ng        947: sub processGroup {
1.41      ng        948:     my ($request)  = shift;
                    949:     my $ctr        = 0;
1.155     albertel  950:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng        951:     my $total      = scalar(@stuchecked)-1;
1.45      ng        952: 
1.396     banghart  953:     foreach my $student (@stuchecked) {
                    954: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel  955: 	$env{'form.student'}        = $uname;
                    956: 	$env{'form.userdom'}        = $udom;
                    957: 	$env{'form.fullname'}       = $fullname;
1.41      ng        958: 	&submission($request,$ctr,$total);
                    959: 	$ctr++;
                    960:     }
                    961:     return '';
1.35      ng        962: }
1.34      ng        963: 
1.44      ng        964: #------------------------------------------------------------------------------------
                    965: #
                    966: #-------------------------- Next few routines handles grading by student, essentially
                    967: #                           handles essay response type problem/part
                    968: #
                    969: #--- Javascript to handle the submission page functionality ---
                    970: sub sub_page_js {
                    971:     my $request = shift;
                    972:     $request->print(<<SUBJAVASCRIPT);
                    973: <script type="text/javascript" language="javascript">
1.71      ng        974:     function updateRadio(formname,id,weight) {
1.125     ng        975: 	var gradeBox = formname["GD_BOX"+id];
                    976: 	var radioButton = formname["RADVAL"+id];
                    977: 	var oldpts = formname["oldpts"+id].value;
1.72      ng        978: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng        979: 	gradeBox.value = pts;
                    980: 	var resetbox = false;
                    981: 	if (isNaN(pts) || pts < 0) {
                    982: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                    983: 	    for (var i=0; i<radioButton.length; i++) {
                    984: 		if (radioButton[i].checked) {
                    985: 		    gradeBox.value = i;
                    986: 		    resetbox = true;
                    987: 		}
                    988: 	    }
                    989: 	    if (!resetbox) {
                    990: 		formtextbox.value = "";
                    991: 	    }
                    992: 	    return;
1.44      ng        993: 	}
1.71      ng        994: 
                    995: 	if (pts > weight) {
                    996: 	    var resp = confirm("You entered a value ("+pts+
                    997: 			       ") greater than the weight for the part. Accept?");
                    998: 	    if (resp == false) {
1.125     ng        999: 		gradeBox.value = oldpts;
1.71      ng       1000: 		return;
                   1001: 	    }
1.44      ng       1002: 	}
1.13      albertel 1003: 
1.71      ng       1004: 	for (var i=0; i<radioButton.length; i++) {
                   1005: 	    radioButton[i].checked=false;
                   1006: 	    if (pts == i && pts != "") {
                   1007: 		radioButton[i].checked=true;
                   1008: 	    }
                   1009: 	}
                   1010: 	updateSelect(formname,id);
1.125     ng       1011: 	formname["stores"+id].value = "0";
1.41      ng       1012:     }
1.5       albertel 1013: 
1.72      ng       1014:     function writeBox(formname,id,pts) {
1.125     ng       1015: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1016: 	if (checkSolved(formname,id) == 'update') {
                   1017: 	    gradeBox.value = pts;
                   1018: 	} else {
1.125     ng       1019: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1020: 	    gradeBox.value = oldpts;
1.125     ng       1021: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1022: 	    for (var i=0; i<radioButton.length; i++) {
                   1023: 		radioButton[i].checked=false;
1.72      ng       1024: 		if (i == oldpts) {
1.71      ng       1025: 		    radioButton[i].checked=true;
                   1026: 		}
                   1027: 	    }
1.41      ng       1028: 	}
1.125     ng       1029: 	formname["stores"+id].value = "0";
1.71      ng       1030: 	updateSelect(formname,id);
                   1031: 	return;
1.41      ng       1032:     }
1.44      ng       1033: 
1.71      ng       1034:     function clearRadBox(formname,id) {
                   1035: 	if (checkSolved(formname,id) == 'noupdate') {
                   1036: 	    updateSelect(formname,id);
                   1037: 	    return;
                   1038: 	}
1.125     ng       1039: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1040: 	for (var i=0; i<gradeSelect.length; i++) {
                   1041: 	    if (gradeSelect[i].selected) {
                   1042: 		var selectx=i;
                   1043: 	    }
                   1044: 	}
1.125     ng       1045: 	var stores = formname["stores"+id];
1.71      ng       1046: 	if (selectx == stores.value) { return };
1.125     ng       1047: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1048: 	gradeBox.value = "";
1.125     ng       1049: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1050: 	for (var i=0; i<radioButton.length; i++) {
                   1051: 	    radioButton[i].checked=false;
                   1052: 	}
                   1053: 	stores.value = selectx;
                   1054:     }
1.5       albertel 1055: 
1.71      ng       1056:     function checkSolved(formname,id) {
1.125     ng       1057: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1058: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1059: 	    if (!reply) {return "noupdate";}
1.120     ng       1060: 	    formname.overRideScore.value = 'yes';
1.41      ng       1061: 	}
1.71      ng       1062: 	return "update";
1.13      albertel 1063:     }
1.71      ng       1064: 
                   1065:     function updateSelect(formname,id) {
1.125     ng       1066: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1067: 	return;
1.41      ng       1068:     }
1.33      ng       1069: 
1.121     ng       1070: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1071:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1072: 	formname.gradeOpt.value = val;
1.71      ng       1073: 	if (val == "Save & Next") {
                   1074: 	    for (i=0;i<=total;i++) {
                   1075: 		for (j=0;j<parttot;j++) {
1.125     ng       1076: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1077: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1078: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1079: 			if (points == "") {
1.125     ng       1080: 			    var name = formname["name"+i].value;
1.129     ng       1081: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1082: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1083: 					       ", part "+partid+". Continue?");
1.71      ng       1084: 			    if (resp == false) {
1.125     ng       1085: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1086: 				return false;
                   1087: 			    }
                   1088: 			}
                   1089: 		    }
                   1090: 		    
                   1091: 		}
                   1092: 	    }
                   1093: 	    
                   1094: 	}
1.121     ng       1095: 	if (val == "Grade Student") {
                   1096: 	    formname.showgrading.value = "yes";
                   1097: 	    if (formname.Status.value == "") {
                   1098: 		formname.Status.value = "Active";
                   1099: 	    }
                   1100: 	    formname.studentNo.value = total;
                   1101: 	}
1.120     ng       1102: 	formname.submit();
                   1103:     }
                   1104: 
1.71      ng       1105: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1106:     function checkSubmitPage(formname,total) {
                   1107: 	noscore = new Array(100);
                   1108: 	var ptr = 0;
                   1109: 	for (i=1;i<total;i++) {
1.125     ng       1110: 	    var partid = formname["q_"+i].value;
1.127     ng       1111: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1112: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1113: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1114: 		if (points == "" && status != "correct_by_student") {
                   1115: 		    noscore[ptr] = i;
                   1116: 		    ptr++;
                   1117: 		}
                   1118: 	    }
                   1119: 	}
                   1120: 	if (ptr != 0) {
                   1121: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1122: 	    var prolist = "";
                   1123: 	    if (ptr == 1) {
                   1124: 		prolist = noscore[0];
                   1125: 	    } else {
                   1126: 		var i = 0;
                   1127: 		while (i < ptr-1) {
                   1128: 		    prolist += noscore[i]+", ";
                   1129: 		    i++;
                   1130: 		}
                   1131: 		prolist += "and "+noscore[i];
                   1132: 	    }
                   1133: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1134: 	    if (resp == false) {
                   1135: 		return false;
                   1136: 	    }
                   1137: 	}
1.45      ng       1138: 
1.71      ng       1139: 	formname.submit();
                   1140:     }
                   1141: </script>
                   1142: SUBJAVASCRIPT
                   1143: }
1.45      ng       1144: 
1.71      ng       1145: #--- javascript for essay type problem --
                   1146: sub sub_page_kw_js {
                   1147:     my $request = shift;
1.80      ng       1148:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1149:     &commonJSfunctions($request);
1.350     albertel 1150: 
1.351     albertel 1151:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1152:     <script text="text/javascript">
                   1153:     function checkInput() {
                   1154:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1155:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1156:       var usrctr = document.msgcenter.usrctr.value;
                   1157:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1158:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1159: 
                   1160:       var msgchk = "";
                   1161:       if (document.msgcenter.subchk.checked) {
                   1162:          msgchk = "msgsub,";
                   1163:       }
                   1164:       var includemsg = 0;
                   1165:       for (var i=1; i<=nmsg; i++) {
                   1166:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1167:           var frmmsg = document.msgcenter["msg"+i];
                   1168:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1169:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1170:           showflg.value = "1";
                   1171:           var chkbox = document.msgcenter["msgn"+i];
                   1172:           if (chkbox.checked) {
                   1173:              msgchk += "savemsg"+i+",";
                   1174:              includemsg = 1;
                   1175:           }
                   1176:       }
                   1177:       if (document.msgcenter.newmsgchk.checked) {
                   1178:          msgchk += "newmsg"+usrctr;
                   1179:          includemsg = 1;
                   1180:       }
                   1181:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1182:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1183:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1184:       includemsg.value = msgchk;
                   1185: 
                   1186:       self.close()
                   1187: 
                   1188:     }
                   1189:     </script>
                   1190: INNERJS
                   1191: 
1.351     albertel 1192:     my $inner_js_highlight_central=<<INNERJS;
                   1193:  <script type="text/javascript">
                   1194:     function updateChoice(flag) {
                   1195:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1196:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1197:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1198:       opener.document.SCORE.refresh.value = "on";
                   1199:       if (opener.document.SCORE.keywords.value!=""){
                   1200:          opener.document.SCORE.submit();
                   1201:       }
                   1202:       self.close()
                   1203:     }
                   1204: </script>
                   1205: INNERJS
                   1206: 
                   1207:     my $start_page_msg_central = 
                   1208:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1209: 				       {'js_ready'  => 1,
                   1210: 					'only_body' => 1,
                   1211: 					'bgcolor'   =>'#FFFFFF',});
                   1212:     my $end_page_msg_central = 
                   1213: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1214: 
                   1215: 
                   1216:     my $start_page_highlight_central = 
                   1217:         &Apache::loncommon::start_page('Highlight Central',
                   1218: 				       $inner_js_highlight_central,
1.350     albertel 1219: 				       {'js_ready'  => 1,
                   1220: 					'only_body' => 1,
                   1221: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1222:     my $end_page_highlight_central = 
1.350     albertel 1223: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1224: 
1.219     www      1225:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1226:     $docopen=~s/^document\.//;
1.71      ng       1227:     $request->print(<<SUBJAVASCRIPT);
                   1228: <script type="text/javascript" language="javascript">
1.45      ng       1229: 
1.44      ng       1230: //===================== Show list of keywords ====================
1.122     ng       1231:   function keywords(formname) {
                   1232:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1233:     if (nret==null) return;
1.122     ng       1234:     formname.keywords.value = nret;
1.44      ng       1235: 
1.122     ng       1236:     if (formname.keywords.value != "") {
1.128     ng       1237: 	formname.refresh.value = "on";
1.122     ng       1238: 	formname.submit();
1.44      ng       1239:     }
                   1240:     return;
                   1241:   }
                   1242: 
                   1243: //===================== Script to view submitted by ==================
                   1244:   function viewSubmitter(submitter) {
                   1245:     document.SCORE.refresh.value = "on";
                   1246:     document.SCORE.NCT.value = "1";
                   1247:     document.SCORE.unamedom0.value = submitter;
                   1248:     document.SCORE.submit();
                   1249:     return;
                   1250:   }
                   1251: 
                   1252: //===================== Script to add keyword(s) ==================
                   1253:   function getSel() {
                   1254:     if (document.getSelection) txt = document.getSelection();
                   1255:     else if (document.selection) txt = document.selection.createRange().text;
                   1256:     else return;
                   1257:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1258:     if (cleantxt=="") {
1.46      ng       1259: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1260: 	return;
                   1261:     }
                   1262:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1263:     if (nret==null) return;
1.127     ng       1264:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1265:     if (document.SCORE.keywords.value != "") {
1.127     ng       1266: 	document.SCORE.refresh.value = "on";
1.44      ng       1267: 	document.SCORE.submit();
                   1268:     }
                   1269:     return;
                   1270:   }
                   1271: 
                   1272: //====================== Script for composing message ==============
1.80      ng       1273:    // preload images
                   1274:    img1 = new Image();
                   1275:    img1.src = "$iconpath/mailbkgrd.gif";
                   1276:    img2 = new Image();
                   1277:    img2.src = "$iconpath/mailto.gif";
                   1278: 
1.44      ng       1279:   function msgCenter(msgform,usrctr,fullname) {
                   1280:     var Nmsg  = msgform.savemsgN.value;
                   1281:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1282:     var subject = msgform.msgsub.value;
1.127     ng       1283:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1284:     re = /msgsub/;
                   1285:     var shwsel = "";
                   1286:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1287:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1288:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1289:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1290: 	var testmsg = "savemsg"+i+",";
                   1291: 	re = new RegExp(testmsg,"g");
1.44      ng       1292: 	shwsel = "";
                   1293: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1294: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1295: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1296: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1297: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1298:     }
1.125     ng       1299:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1300:     shwsel = "";
                   1301:     re = /newmsg/;
                   1302:     if (re.test(msgchk)) { shwsel = "checked" }
                   1303:     newMsg(newmsg,shwsel);
                   1304:     msgTail(); 
                   1305:     return;
                   1306:   }
                   1307: 
1.123     ng       1308:   function checkEntities(strx) {
                   1309:     if (strx.length == 0) return strx;
                   1310:     var orgStr = ["&", "<", ">", '"']; 
                   1311:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1312:     var counter = 0;
                   1313:     while (counter < 4) {
                   1314: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1315: 	counter++;
                   1316:     }
                   1317:     return strx;
                   1318:   }
                   1319: 
                   1320:   function strReplace(strx, orgStr, newStr) {
                   1321:     return strx.split(orgStr).join(newStr);
                   1322:   }
                   1323: 
1.44      ng       1324:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1325:     var height = 70*Nmsg+250;
1.44      ng       1326:     var scrollbar = "no";
                   1327:     if (height > 600) {
                   1328: 	height = 600;
                   1329: 	scrollbar = "yes";
                   1330:     }
1.118     ng       1331:     var xpos = (screen.width-600)/2;
                   1332:     xpos = (xpos < 0) ? '0' : xpos;
                   1333:     var ypos = (screen.height-height)/2-30;
                   1334:     ypos = (ypos < 0) ? '0' : ypos;
                   1335: 
1.206     albertel 1336:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1337:     pWin.focus();
                   1338:     pDoc = pWin.document;
1.219     www      1339:     pDoc.$docopen;
1.351     albertel 1340:     pDoc.write('$start_page_msg_central');
1.76      ng       1341: 
                   1342:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1343:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.398     albertel 1344:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
1.76      ng       1345: 
                   1346:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1347:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1348:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1.44      ng       1349: }
                   1350:     function displaySubject(msg,shwsel) {
1.76      ng       1351:     pDoc = pWin.document;
                   1352:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1353:     pDoc.write("<td>Subject</td>");
                   1354:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1355:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1.44      ng       1356: }
                   1357: 
1.72      ng       1358:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1359:     pDoc = pWin.document;
                   1360:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1361:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
                   1362:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1363:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1.44      ng       1364: }
                   1365: 
                   1366:   function newMsg(newmsg,shwsel) {
1.76      ng       1367:     pDoc = pWin.document;
                   1368:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1369:     pDoc.write("<td align=\\"center\\">New</td>");
                   1370:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1371:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1.44      ng       1372: }
                   1373: 
                   1374:   function msgTail() {
1.76      ng       1375:     pDoc = pWin.document;
                   1376:     pDoc.write("</table>");
                   1377:     pDoc.write("</td></tr></table>&nbsp;");
                   1378:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1379:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1380:     pDoc.write("</form>");
1.351     albertel 1381:     pDoc.write('$end_page_msg_central');
1.128     ng       1382:     pDoc.close();
1.44      ng       1383: }
                   1384: 
                   1385: //====================== Script for keyword highlight options ==============
                   1386:   function kwhighlight() {
                   1387:     var kwclr    = document.SCORE.kwclr.value;
                   1388:     var kwsize   = document.SCORE.kwsize.value;
                   1389:     var kwstyle  = document.SCORE.kwstyle.value;
                   1390:     var redsel = "";
                   1391:     var grnsel = "";
                   1392:     var blusel = "";
                   1393:     if (kwclr=="red")   {var redsel="checked"};
                   1394:     if (kwclr=="green") {var grnsel="checked"};
                   1395:     if (kwclr=="blue")  {var blusel="checked"};
                   1396:     var sznsel = "";
                   1397:     var sz1sel = "";
                   1398:     var sz2sel = "";
                   1399:     if (kwsize=="0")  {var sznsel="checked"};
                   1400:     if (kwsize=="+1") {var sz1sel="checked"};
                   1401:     if (kwsize=="+2") {var sz2sel="checked"};
                   1402:     var synsel = "";
                   1403:     var syisel = "";
                   1404:     var sybsel = "";
                   1405:     if (kwstyle=="")    {var synsel="checked"};
                   1406:     if (kwstyle=="<i>") {var syisel="checked"};
                   1407:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1408:     highlightCentral();
                   1409:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1410:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1411:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1412:     highlightend();
                   1413:     return;
                   1414:   }
                   1415: 
                   1416:   function highlightCentral() {
1.76      ng       1417: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1418:     var xpos = (screen.width-400)/2;
                   1419:     xpos = (xpos < 0) ? '0' : xpos;
                   1420:     var ypos = (screen.height-330)/2-30;
                   1421:     ypos = (ypos < 0) ? '0' : ypos;
                   1422: 
1.206     albertel 1423:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1424:     hwdWin.focus();
                   1425:     var hDoc = hwdWin.document;
1.219     www      1426:     hDoc.$docopen;
1.351     albertel 1427:     hDoc.write('$start_page_highlight_central');
1.76      ng       1428:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.398     albertel 1429:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
1.76      ng       1430: 
                   1431:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1432:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1433:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1.44      ng       1434:   }
                   1435: 
                   1436:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1437:     var hDoc = hwdWin.document;
                   1438:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1439:     hDoc.write("<td align=\\"left\\">");
                   1440:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
                   1441:     hDoc.write("<td align=\\"left\\">");
                   1442:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
                   1443:     hDoc.write("<td align=\\"left\\">");
                   1444:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
                   1445:     hDoc.write("</tr>");
1.44      ng       1446:   }
                   1447: 
                   1448:   function highlightend() { 
1.76      ng       1449:     var hDoc = hwdWin.document;
                   1450:     hDoc.write("</table>");
                   1451:     hDoc.write("</td></tr></table>&nbsp;");
                   1452:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1453:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1454:     hDoc.write("</form>");
1.351     albertel 1455:     hDoc.write('$end_page_highlight_central');
1.128     ng       1456:     hDoc.close();
1.44      ng       1457:   }
                   1458: 
                   1459: </script>
                   1460: SUBJAVASCRIPT
                   1461: }
                   1462: 
1.349     albertel 1463: sub get_increment {
1.348     bowersj2 1464:     my $increment = $env{'form.increment'};
                   1465:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1466:         $increment != .1) {
                   1467:         $increment = 1;
                   1468:     }
                   1469:     return $increment;
                   1470: }
                   1471: 
1.71      ng       1472: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1473: sub gradeBox {
1.322     albertel 1474:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1475:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1476: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1477: 	'/check.gif" height="16" border="0" />';
                   1478:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
                   1479:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
1.398     albertel 1480: 		  '<span class="LC_info">problem weight assigned by computer</span>');
1.71      ng       1481:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1482:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1483: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1484:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.324     albertel 1485:     my $display_part=&get_display_part($partid,$symb);
1.270     albertel 1486:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1487: 				       [$partid]);
                   1488:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1489:     if ($last_resets{$partid}) {
                   1490:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1491:     }
1.71      ng       1492:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1493: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1494:     my $ctr = 0;
1.348     bowersj2 1495:     my $thisweight = 0;
1.349     albertel 1496:     my $increment = &get_increment();
1.71      ng       1497:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1498:     while ($thisweight<=$wgt) {
1.381     albertel 1499: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1500: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1501: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1502: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1503: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1504:         $thisweight += $increment;
1.71      ng       1505: 	$ctr++;
                   1506:     }
                   1507:     $result.='</tr></table>';
                   1508:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1509:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1510: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1511: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1512: 	$wgt.')" /></td>'."\n";
                   1513:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1514: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1515: 	' </td><td>'."\n";
                   1516:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1517: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1518:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1519: 	$result.='<option></option>'.
1.401     albertel 1520: 	    '<option selected="selected">excused</option>';
1.71      ng       1521:     } else {
1.401     albertel 1522: 	$result.='<option selected="selected"></option>'.
1.125     ng       1523: 	    '<option>excused</option>';
1.71      ng       1524:     }
1.125     ng       1525:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1526:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1527:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1528: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1529: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1530: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1531:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1532:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1533:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1534:         $aggtries.'" />'."\n";
1.71      ng       1535:     $result.='</td></tr></table>'."\n";
1.323     banghart 1536:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1537:     return $result;
                   1538: }
1.322     albertel 1539: 
                   1540: sub handback_box {
1.323     banghart 1541:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1542:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1543:     my (@respids);
1.375     albertel 1544:      my @part_response_id = &flatten_responseType($responseType);
                   1545:     foreach my $part_response_id (@part_response_id) {
                   1546:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1547:         if ($part eq $partid) {
1.375     albertel 1548:             push(@respids,$resp);
1.323     banghart 1549:         }
                   1550:     }
1.318     banghart 1551:     my $result;
1.323     banghart 1552:     foreach my $respid (@respids) {
1.322     albertel 1553: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1554: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1555: 	next if (!@$files);
                   1556: 	my $file_counter = 1;
1.313     banghart 1557: 	foreach my $file (@$files) {
1.368     banghart 1558: 	    if ($file =~ /\/portfolio\//) {
                   1559:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1560:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1561:     	        $file_disp = "$name.$ext";
                   1562:     	        $file = $file_path.$file_disp;
                   1563:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1564:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1565:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1566:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.369     banghart 1567:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1.368     banghart 1568:     	        $file_counter++;
                   1569: 	    }
1.322     albertel 1570: 	}
1.313     banghart 1571:     }
1.318     banghart 1572:     return $result;    
1.71      ng       1573: }
1.44      ng       1574: 
1.58      albertel 1575: sub show_problem {
1.382     albertel 1576:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1577:     my $rendered;
1.382     albertel 1578:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1579:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1580:     if ($mode eq 'both' or $mode eq 'text') {
                   1581: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1582: 						       $env{'request.course.id'},
                   1583: 						       undef,\%form);
1.144     albertel 1584:     }
1.58      albertel 1585:     if ($removeform) {
                   1586: 	$rendered=~s|<form(.*?)>||g;
                   1587: 	$rendered=~s|</form>||g;
1.374     albertel 1588: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1589:     }
1.144     albertel 1590:     my $companswer;
                   1591:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1592: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1593: 	$companswer=
                   1594: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1595: 						    $env{'request.course.id'},
                   1596: 						    %form);
1.144     albertel 1597:     }
1.58      albertel 1598:     if ($removeform) {
                   1599: 	$companswer=~s|<form(.*?)>||g;
                   1600: 	$companswer=~s|</form>||g;
1.144     albertel 1601: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1602:     }
                   1603:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1604:     $result.='<table border="0" width="100%">';
1.144     albertel 1605:     if ($viewon) {
                   1606: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1607: 	if ($mode eq 'both' or $mode eq 'text') {
                   1608: 	    $result.='View of the problem - ';
                   1609: 	} else {
                   1610: 	    $result.='Correct answer: ';
                   1611: 	}
1.257     albertel 1612: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1613:     }
                   1614:     if ($mode eq 'both') {
                   1615: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1616: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1617:     } elsif ($mode eq 'text') {
                   1618: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1619:     } elsif ($mode eq 'answer') {
                   1620: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1621:     }
1.58      albertel 1622:     $result.='</td></tr></table>';
                   1623:     $result.='</td></tr></table><br />';
1.71      ng       1624:     return $result;
1.58      albertel 1625: }
1.397     albertel 1626: 
1.396     banghart 1627: sub files_exist {
                   1628:     my ($r, $symb) = @_;
                   1629:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1630: 
1.396     banghart 1631:     foreach my $student (@students) {
                   1632:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1633:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1634: 					      $udom,$uname);
1.396     banghart 1635:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1636:         foreach my $submission (@$string) {
                   1637:             my ($partid,$respid) =
                   1638: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1639:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1640: 					   \%record);
                   1641:             return 1 if (@$files);
1.396     banghart 1642:         }
                   1643:     }
1.397     albertel 1644:     return 0;
1.396     banghart 1645: }
1.397     albertel 1646: 
1.394     banghart 1647: sub download_all_link {
                   1648:     my ($r,$symb) = @_;
1.395     albertel 1649:     my $all_students = 
                   1650: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1651: 
                   1652:     my $parts =
                   1653: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1654: 
1.394     banghart 1655:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1656:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1657:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1658:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1659:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1660: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1661:     return
                   1662: }
1.395     albertel 1663: 
1.44      ng       1664: # --------------------------- show submissions of a student, option to grade 
                   1665: sub submission {
                   1666:     my ($request,$counter,$total) = @_;
                   1667: 
1.257     albertel 1668:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1669:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1670:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1671:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.41      ng       1672: 
1.324     albertel 1673:     my $symb = &get_symb($request); 
                   1674:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1675: 
                   1676:     if (!&canview($usec)) {
1.398     albertel 1677: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1678: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1679: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1680: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1681: 	return;
                   1682:     }
                   1683: 
1.257     albertel 1684:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1685:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1686:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1687:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1688:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1689: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1690: 	'/check.gif" height="16" border="0" />';
1.41      ng       1691: 
1.426     albertel 1692:     my %old_essays;
1.41      ng       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.418     albertel 1754: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($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.417     albertel 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;
1.417     albertel 1798: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       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;
1.426     albertel 1807: 	    %old_essays=&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.417     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)=
1.426     albertel 1945: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 1946: 			if ($osim) {
                   1947: 			    $osim=int($osim*100.0);
1.426     albertel 1948: 			    my %old_course_desc = 
                   1949: 				&Apache::lonnet::coursedescription($ocrsid,
                   1950: 								   {'one_time' => 1});
                   1951: 
                   1952: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 1953: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 1954: 				    $osim,
                   1955: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 1956: 				    $oname,$odom,
1.426     albertel 1957: 				    $old_course_desc{'description'},
1.427     albertel 1958: 				    $old_course_desc{'num'},
1.426     albertel 1959: 				    $old_course_desc{'domain'}).
1.398     albertel 1960: 				'</span></h3><blockquote><i>'.
1.151     albertel 1961: 				&keywords_highlight($oessay).
                   1962: 				'</i></blockquote><hr />';
                   1963: 			}
1.150     albertel 1964: 		    }
1.151     albertel 1965: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 1966: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   1967: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 1968: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 1969: 			my $display_part=&get_display_part($partid,$symb);
1.403     albertel 1970: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   1971: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 1972: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 1973: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   1974: 			if (@$files) {
1.398     albertel 1975: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1.303     banghart 1976: 			    my $file_counter = 0;
1.313     banghart 1977: 			    foreach my $file (@$files) {
1.303     banghart 1978: 			        $file_counter ++;
1.232     albertel 1979: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 1980: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 1981: 			    }
1.236     albertel 1982: 			    $lastsubonly.='<br />';
1.41      ng       1983: 			}
1.151     albertel 1984: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   1985: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   1986: 					 $respid,\%record,$order);
                   1987: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       1988: 		    }
                   1989: 		}
                   1990: 	    }
1.151     albertel 1991: 	}
                   1992: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   1993: 	$request->print($lastsubonly);
1.257     albertel 1994:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 1995: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 1996: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 1997:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       1998: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 1999: 								 $env{'request.course.id'},
1.44      ng       2000: 								 $last,'.submission',
                   2001: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2002:     }
1.120     ng       2003: 
1.121     ng       2004:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2005: 	.$udom.'" />'."\n");
1.41      ng       2006:     
1.44      ng       2007:     # return if view submission with no grading option
1.257     albertel 2008:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2009: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2010: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2011: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 2012: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 2013: 	if (($env{'form.command'} eq 'submission') || 
                   2014: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2015: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2016: 	}
1.180     albertel 2017: 	$request->print($toGrade);
1.41      ng       2018: 	return;
1.180     albertel 2019:     } else {
                   2020: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       2021:     }
1.33      ng       2022: 
1.121     ng       2023:     # essay grading message center
1.257     albertel 2024:     if ($env{'form.handgrade'} eq 'yes') {
                   2025: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2026: 	my $msgfor = $givenn.' '.$lastname;
                   2027: 	if (scalar(@col_fullnames) > 0) {
                   2028: 	    my $lastone = pop @col_fullnames;
                   2029: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   2030: 	}
                   2031: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       2032: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2033: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2034: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2035: 	    ',\''.$msgfor.'\');" target="_self">'.
1.350     albertel 2036: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
                   2037: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2038: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2039: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2040: 	    '<br />&nbsp;('.
                   2041: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       2042: 	$request->print($result);
1.118     ng       2043:     }
1.300     albertel 2044:     if ($perm{'vgr'}) {
1.297     www      2045: 	$request->print('<br />'.
1.300     albertel 2046: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2047: 						   $uname,$udom,'check'));
1.297     www      2048:     }
1.300     albertel 2049:     if ($perm{'opa'}) {
1.297     www      2050: 	$request->print('<br />'.
1.300     albertel 2051: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2052: 					 $uname,$udom,$symb,'check'));
1.297     www      2053:     }
1.41      ng       2054: 
                   2055:     my %seen = ();
                   2056:     my @partlist;
1.129     ng       2057:     my @gradePartRespid;
1.375     albertel 2058:     my @part_response_id = &flatten_responseType($responseType);
                   2059:     foreach my $part_response_id (@part_response_id) {
                   2060:     	my ($partid,$respid) = @{ $part_response_id };
                   2061: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2062: 	next if ($seen{$partid} > 0);
1.41      ng       2063: 	$seen{$partid}++;
1.393     albertel 2064: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2065: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2066: 	push @partlist,$partid;
1.129     ng       2067: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2068: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2069:     }
1.45      ng       2070:     $result='<input type="hidden" name="partlist'.$counter.
                   2071: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2072:     $result.='<input type="hidden" name="gradePartRespid'.
                   2073: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2074:     my $ctr = 0;
                   2075:     while ($ctr < scalar(@partlist)) {
                   2076: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2077: 	    $partlist[$ctr].'" />'."\n";
                   2078: 	$ctr++;
                   2079:     }
                   2080:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       2081: 
                   2082:     # print end of form
                   2083:     if ($counter == $total) {
1.297     www      2084: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2085: 	$endform.='<input type="button" value="Save & Next" '.
                   2086: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2087: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2088: 	my $ntstu ='<select name="NTSTU">'.
                   2089: 	    '<option>1</option><option>2</option>'.
                   2090: 	    '<option>3</option><option>5</option>'.
                   2091: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2092: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2093: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.119     ng       2094: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2095: 	$endform.='<input type="button" value="Previous" '.
1.417     albertel 2096: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.126     ng       2097: 	    '<input type="button" value="Next" '.
1.417     albertel 2098: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.126     ng       2099: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2100:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2101:             "' name='increment' />";
1.45      ng       2102: 	$endform.='</td><tr></table></form>';
1.324     albertel 2103: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2104: 	$request->print($endform);
                   2105:     }
                   2106:     return '';
1.38      ng       2107: }
                   2108: 
1.44      ng       2109: #--- Retrieve the last submission for all the parts
1.38      ng       2110: sub get_last_submission {
1.119     ng       2111:     my ($returnhash)=@_;
1.46      ng       2112:     my (@string,$timestamp);
1.119     ng       2113:     if ($$returnhash{'version'}) {
1.46      ng       2114: 	my %lasthash=();
                   2115: 	my ($version);
1.119     ng       2116: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2117: 	    foreach my $key (sort(split(/\:/,
                   2118: 					$$returnhash{$version.':keys'}))) {
                   2119: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2120: 		$timestamp = 
                   2121: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2122: 	    }
                   2123: 	}
1.397     albertel 2124: 	foreach my $key (keys(%lasthash)) {
                   2125: 	    next if ($key !~ /\.submission$/);
                   2126: 
                   2127: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2128: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2129: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2130: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2131: 	}
                   2132:     }
1.397     albertel 2133:     if (!@string) {
                   2134: 	$string[0] =
1.398     albertel 2135: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2136:     }
                   2137:     return (\@string,\$timestamp);
1.38      ng       2138: }
1.35      ng       2139: 
1.44      ng       2140: #--- High light keywords, with style choosen by user.
1.38      ng       2141: sub keywords_highlight {
1.44      ng       2142:     my $string    = shift;
1.257     albertel 2143:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2144:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2145:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2146:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2147:     foreach my $keyword (@keylist) {
                   2148: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2149:     }
                   2150:     return $string;
1.38      ng       2151: }
1.36      ng       2152: 
1.44      ng       2153: #--- Called from submission routine
1.38      ng       2154: sub processHandGrade {
1.41      ng       2155:     my ($request) = shift;
1.324     albertel 2156:     my $symb   = &get_symb($request);
                   2157:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2158:     my $button = $env{'form.gradeOpt'};
                   2159:     my $ngrade = $env{'form.NCT'};
                   2160:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2161:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2162:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2163: 
1.44      ng       2164:     if ($button eq 'Save & Next') {
                   2165: 	my $ctr = 0;
                   2166: 	while ($ctr < $ngrade) {
1.257     albertel 2167: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2168: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2169: 	    if ($errorflag eq 'no_score') {
                   2170: 		$ctr++;
                   2171: 		next;
                   2172: 	    }
1.104     albertel 2173: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2174: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2175: 		$ctr++;
                   2176: 		next;
                   2177: 	    }
1.257     albertel 2178: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2179: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2180: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2181:             my ($feedurl,$showsymb) =
                   2182: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2183: 	    my $messagetail;
1.62      albertel 2184: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2185: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2186: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2187: 		$subject.=' ['.$restitle.']';
1.44      ng       2188: 		my (@msgnum) = split(/,/,$includemsg);
                   2189: 		foreach (@msgnum) {
1.257     albertel 2190: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2191: 		}
1.80      ng       2192: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2193: 		if ($env{'form.withgrades'.$ctr}) {
                   2194: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2195: 		    $messagetail = " for <a href=\"".
1.418     albertel 2196: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2197: 		}
                   2198: 		$msgstatus = 
                   2199:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2200: 						     $message.$messagetail,
1.418     albertel 2201:                                                      undef,$feedurl,undef,
1.386     raeburn  2202:                                                      undef,undef,$showsymb,
                   2203:                                                      $restitle);
                   2204: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2205: 				$msgstatus);
1.44      ng       2206: 	    }
1.257     albertel 2207: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2208: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2209: 		foreach my $collabstr (@collabstrs) {
                   2210: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2211: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2212: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2213: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2214: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2215: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2216: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2217: 			    next;
1.418     albertel 2218: 			} elsif ($message ne '') {
                   2219: 			    my ($baseurl,$showsymb) = 
                   2220: 				&get_feedurl_and_symb($symb,$collaborator,
                   2221: 						      $udom);
                   2222: 			    if ($env{'form.withgrades'.$ctr}) {
                   2223: 				$messagetail = " for <a href=\"".
1.386     raeburn  2224:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2225: 			    }
1.418     albertel 2226: 			    $msgstatus = 
                   2227: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2228: 			}
1.44      ng       2229: 		    }
                   2230: 		}
                   2231: 	    }
                   2232: 	    $ctr++;
                   2233: 	}
                   2234:     }
                   2235: 
1.257     albertel 2236:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2237: 	# Keywords sorted in alphabatical order
1.257     albertel 2238: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2239: 	my %keyhash = ();
1.257     albertel 2240: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2241: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2242: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2243: 	$env{'form.keywords'} = join(' ',@keywords);
                   2244: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2245: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2246: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2247: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2248: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2249: 
                   2250: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2251: 	# New messages are saved in env for the next student.
1.119     ng       2252: 	# All messages are saved in nohist_handgrade.db
                   2253: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2254: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2255: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2256: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2257: 		$idx++;
                   2258: 	    }
                   2259: 	    $ctr++;
1.41      ng       2260: 	}
1.119     ng       2261: 	$ctr = 0;
                   2262: 	while ($ctr < $ngrade) {
1.257     albertel 2263: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2264: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2265: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2266: 		$idx++;
                   2267: 	    }
                   2268: 	    $ctr++;
1.41      ng       2269: 	}
1.257     albertel 2270: 	$env{'form.savemsgN'} = --$idx;
                   2271: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2272: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2273: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2274:     }
1.44      ng       2275:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2276:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2277:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2278: 	my ($ctr,$total) = (0,0);
                   2279: 	while ($ctr < $ngrade) {
1.257     albertel 2280: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2281: 	    $ctr++;
                   2282: 	}
1.257     albertel 2283: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2284: 	$ctr = 0;
                   2285: 	while ($ctr < $total) {
1.257     albertel 2286: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2287: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2288: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2289: 	    &submission($request,$ctr,$total-1);
1.41      ng       2290: 	    $ctr++;
                   2291: 	}
                   2292: 	return '';
                   2293:     }
1.36      ng       2294: 
1.121     ng       2295: # Go directly to grade student - from submission or link from chart page
1.120     ng       2296:     if ($button eq 'Grade Student') {
1.324     albertel 2297: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2298: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2299: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2300: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2301: 	&submission($request,0,0);
                   2302: 	return '';
                   2303:     }
                   2304: 
1.44      ng       2305:     # Get the next/previous one or group of students
1.257     albertel 2306:     my $firststu = $env{'form.unamedom0'};
                   2307:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2308:     my $ctr = 2;
1.41      ng       2309:     while ($laststu eq '') {
1.257     albertel 2310: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2311: 	$ctr++;
                   2312: 	$laststu = $firststu if ($ctr > $ngrade);
                   2313:     }
1.44      ng       2314: 
1.41      ng       2315:     my (@parsedlist,@nextlist);
                   2316:     my ($nextflg) = 0;
1.294     albertel 2317:     foreach (sort 
                   2318: 	     {
                   2319: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2320: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2321: 		 }
                   2322: 		 return $a cmp $b;
                   2323: 	     } (keys(%$fullname))) {
1.41      ng       2324: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2325: 	    push @parsedlist,$_;
                   2326: 	}
                   2327: 	$nextflg = 1 if ($_ eq $laststu);
                   2328: 	if ($button eq 'Previous') {
                   2329: 	    last if ($_ eq $firststu);
                   2330: 	    push @parsedlist,$_;
                   2331: 	}
                   2332:     }
                   2333:     $ctr = 0;
                   2334:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2335:     my ($partlist) = &response_type($symb);
1.41      ng       2336:     foreach my $student (@parsedlist) {
1.257     albertel 2337: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2338: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2339: 	
                   2340: 	if ($submitonly eq 'queued') {
                   2341: 	    my %queue_status = 
                   2342: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2343: 							$udom,$uname);
                   2344: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2345: 	}
                   2346: 
1.156     albertel 2347: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2348: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2349: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2350: 	    my $submitted = 0;
1.248     albertel 2351: 	    my $ungraded = 0;
                   2352: 	    my $incorrect = 0;
1.145     albertel 2353: 	    foreach (keys(%status)) {
                   2354: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2355: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2356: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2357: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2358: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2359: 		    $submitted = 0;
                   2360: 		}
1.41      ng       2361: 	    }
1.156     albertel 2362: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2363: 				     $submitonly eq 'incorrect' ||
                   2364: 				     $submitonly eq 'graded'));
1.248     albertel 2365: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2366: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2367: 	}
                   2368: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2369: 	last if ($ctr == $ntstu);
1.41      ng       2370: 	$ctr++;
                   2371:     }
1.36      ng       2372: 
1.41      ng       2373:     $ctr = 0;
                   2374:     my $total = scalar(@nextlist)-1;
1.39      ng       2375: 
1.41      ng       2376:     foreach (sort @nextlist) {
                   2377: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2378: 	$env{'form.student'}  = $uname;
                   2379: 	$env{'form.userdom'}  = $udom;
                   2380: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2381: 	&submission($request,$ctr,$total);
                   2382: 	$ctr++;
                   2383:     }
                   2384:     if ($total < 0) {
1.398     albertel 2385: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
1.41      ng       2386: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2387: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2388: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2389: 	$request->print($the_end);
                   2390:     }
                   2391:     return '';
1.38      ng       2392: }
1.36      ng       2393: 
1.44      ng       2394: #---- Save the score and award for each student, if changed
1.38      ng       2395: sub saveHandGrade {
1.324     albertel 2396:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2397:     my @version_parts;
1.104     albertel 2398:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2399: 					   $env{'request.course.id'});
1.104     albertel 2400:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2401:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2402:     my @parts_graded;
1.77      ng       2403:     my %newrecord  = ();
                   2404:     my ($pts,$wgt) = ('','');
1.269     raeburn  2405:     my %aggregate = ();
                   2406:     my $aggregateflag = 0;
1.301     albertel 2407:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2408:     foreach my $new_part (@parts) {
1.337     banghart 2409: 	#collaborator ($submi may vary for different parts
1.259     banghart 2410: 	if ($submitter && $new_part ne $part) { next; }
                   2411: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2412: 	if ($dropMenu eq 'excused') {
1.259     banghart 2413: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2414: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2415: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2416: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2417: 		}
1.364     banghart 2418: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2419: 	    }
1.125     ng       2420: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2421: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2422: 	    foreach my $key (keys (%record)) {
1.259     banghart 2423: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2424: 	    }
1.259     banghart 2425: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2426: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2427:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2428: 
                   2429:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2430: 					       [$new_part]);
                   2431:             my $aggtries =$totaltries;
1.269     raeburn  2432:             if ($last_resets{$new_part}) {
1.270     albertel 2433:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2434: 					   $new_part);
1.269     raeburn  2435:             }
1.270     albertel 2436: 
                   2437:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2438:             if ($aggtries > 0) {
1.327     albertel 2439:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2440:                 $aggregateflag = 1;
                   2441:             }
1.125     ng       2442: 	} elsif ($dropMenu eq '') {
1.259     banghart 2443: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2444: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2445: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2446: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2447: 		next;
                   2448: 	    }
1.259     banghart 2449: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2450: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2451: 	    my $partial= $pts/$wgt;
1.259     banghart 2452: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2453: 		#do not update score for part if not changed.
1.346     banghart 2454:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2455: 		next;
1.251     banghart 2456: 	    } else {
1.259     banghart 2457: 	        push @parts_graded, $new_part;
1.153     albertel 2458: 	    }
1.259     banghart 2459: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2460: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2461: 	    }
1.259     banghart 2462: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2463: 	    if ($partial == 0) {
1.153     albertel 2464: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2465: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2466: 		}
1.41      ng       2467: 	    } else {
1.153     albertel 2468: 		if ($record{$reckey} ne 'correct_by_override') {
                   2469: 		    $newrecord{$reckey} = 'correct_by_override';
                   2470: 		}
                   2471: 	    }	    
                   2472: 	    if ($submitter && 
1.259     banghart 2473: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2474: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2475: 	    }
1.259     banghart 2476: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2477: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2478: 	}
1.259     banghart 2479: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2480: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2481: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2482: 	        $dropMenu eq 'reset status')
                   2483: 	   {
1.342     banghart 2484: 	    push (@version_parts,$new_part);
1.259     banghart 2485: 	}
1.41      ng       2486:     }
1.301     albertel 2487:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2488:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2489: 
1.344     albertel 2490:     if (%newrecord) {
                   2491:         if (@version_parts) {
1.364     banghart 2492:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2493:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2494: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2495: 	    foreach my $new_part (@version_parts) {
                   2496: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2497: 				$new_part,\%newrecord);
                   2498: 	    }
1.259     banghart 2499:         }
1.44      ng       2500: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2501: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2502: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2503: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2504:     }
1.269     raeburn  2505:     if ($aggregateflag) {
                   2506:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2507: 			      $cdom,$cnum);
1.269     raeburn  2508:     }
1.301     albertel 2509:     return ('',$pts,$wgt);
1.36      ng       2510: }
1.322     albertel 2511: 
1.380     albertel 2512: sub check_and_remove_from_queue {
                   2513:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2514:     my @ungraded_parts;
                   2515:     foreach my $part (@{$parts}) {
                   2516: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2517: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2518: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2519: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2520: 		) {
                   2521: 	    push(@ungraded_parts, $part);
                   2522: 	}
                   2523:     }
                   2524:     if ( !@ungraded_parts ) {
                   2525: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2526: 					       $cnum,$domain,$stuname);
                   2527:     }
                   2528: }
                   2529: 
1.337     banghart 2530: sub handback_files {
                   2531:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2532:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2533:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2534: 
                   2535:     my @part_response_id = &flatten_responseType($responseType);
                   2536:     foreach my $part_response_id (@part_response_id) {
                   2537:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2538: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2539:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2540:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2541:                 my $file_counter = 1;
1.367     albertel 2542: 		my $file_msg;
1.337     banghart 2543:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2544:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2545:                     my ($directory,$answer_file) = 
                   2546:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2547:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2548: 		        &file_name_version_ext($answer_file);
1.355     banghart 2549: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2550: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2551: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2552:                     # fix file name
                   2553:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2554:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2555:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2556:             	                                $save_file_name);
1.337     banghart 2557:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2558:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2559:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2560:                     } else {
1.360     banghart 2561:                         # mark the file as read only
                   2562:                         my @files = ($save_file_name);
1.372     albertel 2563:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2564:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2565: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2566: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2567: 			}
                   2568:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2569: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2570: 
1.337     banghart 2571:                     }
                   2572:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2573:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2574:                     $file_counter++;
                   2575:                 }
1.367     albertel 2576: 		my $subject = "File Handed Back by Instructor ";
                   2577: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2578: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2579: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2580: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2581: 		my ($feedurl,$showsymb) = 
                   2582: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2583:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2584: 		my $msgstatus = 
                   2585:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2586: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2587:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2588:             }
                   2589:         }
1.338     banghart 2590:     return;
1.337     banghart 2591: }
                   2592: 
1.418     albertel 2593: sub get_feedurl_and_symb {
                   2594:     my ($symb,$uname,$udom) = @_;
                   2595:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2596:     $url = &Apache::lonnet::clutter($url);
                   2597:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2598: 					$symb,$udom,$uname);
                   2599:     if ($encrypturl =~ /^yes$/i) {
                   2600: 	&Apache::lonenc::encrypted(\$url,1);
                   2601: 	&Apache::lonenc::encrypted(\$symb,1);
                   2602:     }
                   2603:     return ($url,$symb);
                   2604: }
                   2605: 
1.313     banghart 2606: sub get_submitted_files {
                   2607:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2608:     my @files;
                   2609:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2610:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2611:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2612:     	    push(@files,$file_url.$file);
                   2613:         }
                   2614:     }
                   2615:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2616:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2617:     }
                   2618:     return (\@files);
                   2619: }
1.322     albertel 2620: 
1.269     raeburn  2621: # ----------- Provides number of tries since last reset.
                   2622: sub get_num_tries {
                   2623:     my ($record,$last_reset,$part) = @_;
                   2624:     my $timestamp = '';
                   2625:     my $num_tries = 0;
                   2626:     if ($$record{'version'}) {
                   2627:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2628:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2629:                 $timestamp = $$record{$version.':timestamp'};
                   2630:                 if ($timestamp > $last_reset) {
                   2631:                     $num_tries ++;
                   2632:                 } else {
                   2633:                     last;
                   2634:                 }
                   2635:             }
                   2636:         }
                   2637:     }
                   2638:     return $num_tries;
                   2639: }
                   2640: 
                   2641: # ----------- Determine decrements required in aggregate totals 
                   2642: sub decrement_aggs {
                   2643:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2644:     my %decrement = (
                   2645:                         attempts => 0,
                   2646:                         users => 0,
                   2647:                         correct => 0
                   2648:                     );
                   2649:     $decrement{'attempts'} = $aggtries;
                   2650:     if ($solvedstatus =~ /^correct/) {
                   2651:         $decrement{'correct'} = 1;
                   2652:     }
                   2653:     if ($aggtries == $totaltries) {
                   2654:         $decrement{'users'} = 1;
                   2655:     }
                   2656:     foreach my $type (keys (%decrement)) {
                   2657:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2658:     }
                   2659:     return;
                   2660: }
                   2661: 
                   2662: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2663: sub get_last_resets {
1.270     albertel 2664:     my ($symb,$courseid,$partids) =@_;
                   2665:     my %last_resets;
1.269     raeburn  2666:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2667:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2668:     my @keys;
                   2669:     foreach my $part (@{$partids}) {
                   2670: 	push(@keys,"$symb\0$part\0resettime");
                   2671:     }
                   2672:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2673: 				     $cdom,$cname);
                   2674:     foreach my $part (@{$partids}) {
                   2675: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2676:     }
1.270     albertel 2677:     return %last_resets;
1.269     raeburn  2678: }
                   2679: 
1.251     banghart 2680: # ----------- Handles creating versions for portfolio files as answers
                   2681: sub version_portfiles {
1.343     banghart 2682:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2683:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2684:     my @returned_keys;
1.255     banghart 2685:     my $parts = join('|', @$parts_graded);
1.359     www      2686:     my $portfolio_root = &propath($domain,$stu_name).
                   2687: 	'/userfiles/portfolio';
1.277     albertel 2688:     foreach my $key (keys(%$record)) {
1.259     banghart 2689:         my $new_portfiles;
1.263     banghart 2690:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2691:             my @versioned_portfiles;
1.367     albertel 2692:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2693:             foreach my $file (@portfiles) {
1.306     banghart 2694:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2695:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2696: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2697: 		    &file_name_version_ext($answer_file);
1.306     banghart 2698:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2699:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2700:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2701:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2702:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2703:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2704:                         [$directory.$new_answer],
1.306     banghart 2705:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2706:                 }
1.252     banghart 2707:             }
1.343     banghart 2708:             $$record{$key} = join(',',@versioned_portfiles);
                   2709:             push(@returned_keys,$key);
1.251     banghart 2710:         }
                   2711:     } 
1.343     banghart 2712:     return (@returned_keys);   
1.305     banghart 2713: }
                   2714: 
1.307     banghart 2715: sub get_next_version {
1.341     banghart 2716:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2717:     my $version;
                   2718:     foreach my $row (@$dir_list) {
                   2719:         my ($file) = split(/\&/,$row,2);
                   2720:         my ($file_name,$file_version,$file_ext) =
                   2721: 	    &file_name_version_ext($file);
                   2722:         if (($file_name eq $answer_name) && 
                   2723: 	    ($file_ext eq $answer_ext)) {
                   2724:                 # gets here if filename and extension match, regardless of version
                   2725:                 if ($file_version ne '') {
                   2726:                 # a versioned file is found  so save it for later
                   2727:                 if ($file_version > $version) {
                   2728: 		    $version = $file_version;
                   2729: 	        }
                   2730:             }
                   2731:         }
                   2732:     } 
                   2733:     $version ++;
                   2734:     return($version);
                   2735: }
                   2736: 
1.305     banghart 2737: sub version_selected_portfile {
1.306     banghart 2738:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2739:     my ($answer_name,$answer_ver,$answer_ext) =
                   2740:         &file_name_version_ext($file_name);
                   2741:     my $new_answer;
                   2742:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2743:     if($env{'form.copy'} eq '-1') {
                   2744:         &Apache::lonnet::logthis('problem getting file '.$file_name);
                   2745:         $new_answer = 'problem getting file';
                   2746:     } else {
                   2747:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2748:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2749:                             $stu_name,$domain,'copy',
                   2750: 		        '/portfolio'.$directory.$new_answer);
                   2751:     }    
                   2752:     return ($new_answer);
1.251     banghart 2753: }
                   2754: 
1.304     albertel 2755: sub file_name_version_ext {
                   2756:     my ($file)=@_;
                   2757:     my @file_parts = split(/\./, $file);
                   2758:     my ($name,$version,$ext);
                   2759:     if (@file_parts > 1) {
                   2760: 	$ext=pop(@file_parts);
                   2761: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2762: 	    $version=pop(@file_parts);
                   2763: 	}
                   2764: 	$name=join('.',@file_parts);
                   2765:     } else {
                   2766: 	$name=join('.',@file_parts);
                   2767:     }
                   2768:     return($name,$version,$ext);
                   2769: }
                   2770: 
1.44      ng       2771: #--------------------------------------------------------------------------------------
                   2772: #
                   2773: #-------------------------- Next few routines handles grading by section or whole class
                   2774: #
                   2775: #--- Javascript to handle grading by section or whole class
1.42      ng       2776: sub viewgrades_js {
                   2777:     my ($request) = shift;
                   2778: 
1.41      ng       2779:     $request->print(<<VIEWJAVASCRIPT);
                   2780: <script type="text/javascript" language="javascript">
1.45      ng       2781:    function writePoint(partid,weight,point) {
1.125     ng       2782: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2783: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2784: 	if (point == "textval") {
1.125     ng       2785: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2786: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2787: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2788: 		var resetbox = false;
                   2789: 		for (var i=0; i<radioButton.length; i++) {
                   2790: 		    if (radioButton[i].checked) {
                   2791: 			textbox.value = i;
                   2792: 			resetbox = true;
                   2793: 		    }
                   2794: 		}
                   2795: 		if (!resetbox) {
                   2796: 		    textbox.value = "";
                   2797: 		}
                   2798: 		return;
                   2799: 	    }
1.109     matthew  2800: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2801: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2802: 				   ") greater than the weight for the part. Accept?");
                   2803: 		if (resp == false) {
                   2804: 		    textbox.value = "";
                   2805: 		    return;
                   2806: 		}
                   2807: 	    }
1.42      ng       2808: 	    for (var i=0; i<radioButton.length; i++) {
                   2809: 		radioButton[i].checked=false;
1.109     matthew  2810: 		if (parseFloat(point) == i) {
1.42      ng       2811: 		    radioButton[i].checked=true;
                   2812: 		}
                   2813: 	    }
1.41      ng       2814: 
1.42      ng       2815: 	} else {
1.125     ng       2816: 	    textbox.value = parseFloat(point);
1.42      ng       2817: 	}
1.41      ng       2818: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2819: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2820: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2821: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2822: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2823: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2824: 	    if (saveval != "correct") {
                   2825: 		scorename.value = point;
1.43      ng       2826: 		if (selname[0].selected != true) {
                   2827: 		    selname[0].selected = true;
                   2828: 		}
1.42      ng       2829: 	    }
                   2830: 	}
1.125     ng       2831: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2832:     }
                   2833: 
                   2834:     function writeRadText(partid,weight) {
1.125     ng       2835: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2836: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2837:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2838: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2839: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2840: 	    for (var i=0; i<radioButton.length; i++) {
                   2841: 		radioButton[i].checked=false;
                   2842: 
                   2843: 	    }
                   2844: 	    textbox.value = "";
                   2845: 
                   2846: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2847: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2848: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2849: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2850: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2851: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2852: 		if ((saveval != "correct") || override) {
1.42      ng       2853: 		    scorename.value = "";
1.125     ng       2854: 		    if (selval[1].selected) {
                   2855: 			selname[1].selected = true;
                   2856: 		    } else {
                   2857: 			selname[2].selected = true;
                   2858: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   2859: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   2860: 		    }
1.42      ng       2861: 		}
                   2862: 	    }
1.43      ng       2863: 	} else {
                   2864: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2865: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2866: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2867: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2868: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2869: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2870: 		if ((saveval != "correct") || override) {
1.125     ng       2871: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       2872: 		    selname[0].selected = true;
                   2873: 		}
                   2874: 	    }
                   2875: 	}	    
1.42      ng       2876:     }
                   2877: 
                   2878:     function changeSelect(partid,user) {
1.125     ng       2879: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2880: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       2881: 	var point  = textbox.value;
1.125     ng       2882: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       2883: 
1.109     matthew  2884: 	if (isNaN(point) || parseFloat(point) < 0) {
                   2885: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       2886: 	    textbox.value = "";
                   2887: 	    return;
                   2888: 	}
1.109     matthew  2889: 	if (parseFloat(point) > parseFloat(weight)) {
                   2890: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2891: 			       ") greater than the weight of the part. Accept?");
                   2892: 	    if (resp == false) {
                   2893: 		textbox.value = "";
                   2894: 		return;
                   2895: 	    }
                   2896: 	}
1.42      ng       2897: 	selval[0].selected = true;
                   2898:     }
                   2899: 
                   2900:     function changeOneScore(partid,user) {
1.125     ng       2901: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2902: 	if (selval[1].selected || selval[2].selected) {
                   2903: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   2904: 	    if (selval[2].selected) {
                   2905: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   2906: 	    }
1.269     raeburn  2907:         }
1.42      ng       2908:     }
                   2909: 
                   2910:     function resetEntry(numpart) {
                   2911: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       2912: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   2913: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   2914: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   2915: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       2916: 	    for (var i=0; i<radioButton.length; i++) {
                   2917: 		radioButton[i].checked=false;
                   2918: 
                   2919: 	    }
                   2920: 	    textbox.value = "";
                   2921: 	    selval[0].selected = true;
                   2922: 
                   2923: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2924: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2925: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2926: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2927: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   2928: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   2929: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   2930: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2931: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2932: 		if (saveselval == "excused") {
1.43      ng       2933: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       2934: 		} else {
1.43      ng       2935: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       2936: 		}
                   2937: 	    }
1.41      ng       2938: 	}
1.42      ng       2939:     }
                   2940: 
1.41      ng       2941: </script>
                   2942: VIEWJAVASCRIPT
1.42      ng       2943: }
                   2944: 
1.44      ng       2945: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       2946: sub viewgrades {
                   2947:     my ($request) = shift;
                   2948:     &viewgrades_js($request);
1.41      ng       2949: 
1.324     albertel 2950:     my ($symb) = &get_symb($request);
1.168     albertel 2951:     #need to make sure we have the correct data for later EXT calls, 
                   2952:     #thus invalidate the cache
                   2953:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 2954:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   2955:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 2956:     &Apache::lonnet::clear_EXT_cache_status();
                   2957: 
1.398     albertel 2958:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   2959:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       2960: 
                   2961:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 2962:     $result.=&jscriptNform($symb);
1.41      ng       2963: 
1.44      ng       2964:     #beginning of class grading form
1.41      ng       2965:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 2966: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       2967: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.257     albertel 2968: 	'<input type="hidden" name="section" value="'.$env{'form.section'}.'" />'."\n".
                   2969: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   2970: 	'<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
                   2971: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       2972: 
1.126     ng       2973:     my $sectionClass;
1.430     banghart 2974:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 2975:     if ($env{'form.section'} eq 'all') {
1.126     ng       2976: 	$sectionClass='Class </h3>';
1.257     albertel 2977:     } elsif ($env{'form.section'} eq 'none') {
1.431   ! banghart 2978: 	$sectionClass=&mt('Students in no Section').'</h3>';
1.52      albertel 2979:     } else {
1.431   ! banghart 2980: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
1.52      albertel 2981:     }
1.431   ! banghart 2982:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
1.52      albertel 2983:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   2984: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       2985:     #radio buttons/text box for assigning points for a section or class.
                   2986:     #handles different parts of a problem
1.375     albertel 2987:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       2988:     my %weight = ();
                   2989:     my $ctsparts = 0;
1.41      ng       2990:     $result.='<table border="0">';
1.45      ng       2991:     my %seen = ();
1.375     albertel 2992:     my @part_response_id = &flatten_responseType($responseType);
                   2993:     foreach my $part_response_id (@part_response_id) {
                   2994:     	my ($partid,$respid) = @{ $part_response_id };
                   2995: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       2996: 	next if $seen{$partid};
                   2997: 	$seen{$partid}++;
1.375     albertel 2998: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       2999: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3000: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3001: 
1.44      ng       3002: 	$result.='<input type="hidden" name="partid_'.
                   3003: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3004: 	$result.='<input type="hidden" name="weight_'.
                   3005: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3006: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 3007: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3008: 	$result.='<table border="0"><tr>';  
1.41      ng       3009: 	my $ctr = 0;
1.42      ng       3010: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3011: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3012: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3013: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3014: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3015: 	    $ctr++;
                   3016: 	}
                   3017: 	$result.='</tr></table>';
1.44      ng       3018: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3019: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3020: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3021: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   3022: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3023: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3024: 		$weight{$partid}.')"> '.
1.401     albertel 3025: 	    '<option selected="selected"> </option>'.
1.125     ng       3026: 	    '<option>excused</option>'.
1.265     www      3027: 	    '<option>reset status</option></select></td>'.
1.266     albertel 3028:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       3029: 	$ctsparts++;
1.41      ng       3030:     }
1.52      albertel 3031:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   3032: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3033:     $result.='<input type="button" value="Revert to Default" '.
1.417     albertel 3034: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
1.41      ng       3035: 
1.44      ng       3036:     #table listing all the students in a section/class
                   3037:     #header of table
1.126     ng       3038:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       3039:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       3040: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       3041: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 3042:     my (@parts) = sort(&getpartlist($symb));
                   3043:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3044:     my @partids = ();
1.41      ng       3045:     foreach my $part (@parts) {
                   3046: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3047: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3048: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3049: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3050:         push(@partids, $partid);
1.324     albertel 3051: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3052: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 3053: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   3054: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       3055: 	    next;
1.207     albertel 3056: 	} else {
                   3057: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3058: 	}
1.53      albertel 3059: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 3060: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       3061:     }
                   3062:     $result.='</tr>';
1.44      ng       3063: 
1.270     albertel 3064:     my %last_resets = 
                   3065: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3066: 
1.41      ng       3067:     #get info for each student
1.44      ng       3068:     #list all the students - with points and grade status
1.257     albertel 3069:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3070:     my $ctr = 0;
1.294     albertel 3071:     foreach (sort 
                   3072: 	     {
                   3073: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3074: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3075: 		 }
                   3076: 		 return $a cmp $b;
                   3077: 	     } (keys(%$fullname))) {
1.126     ng       3078: 	$ctr++;
1.324     albertel 3079: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3080: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3081:     }
                   3082:     $result.='</table></td></tr></table>';
                   3083:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3084:     $result.='<input type="button" value="Save" '.
1.417     albertel 3085: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3086:     if (scalar(%$fullname) eq 0) {
                   3087: 	my $colspan=3+scalar(@parts);
1.398     albertel 3088: 	$result='<span class="LC_warning">There are no students in section "'.$env{'form.section'}.
                   3089: 	    '" with enrollment status "'.$env{'form.Status'}.'" to modify or grade.</span>';
1.96      albertel 3090:     }
1.324     albertel 3091:     $result.=&show_grading_menu_form($symb);
1.41      ng       3092:     return $result;
                   3093: }
                   3094: 
1.44      ng       3095: #--- call by previous routine to display each student
1.41      ng       3096: sub viewstudentgrade {
1.324     albertel 3097:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3098:     my ($uname,$udom) = split(/:/,$student);
                   3099:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3100:     my %aggregates = (); 
1.233     albertel 3101:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3102: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3103: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3104: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3105: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3106: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3107:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3108:     foreach my $apart (@$parts) {
                   3109: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3110: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3111:         $result.='<td align="center">';
1.269     raeburn  3112:         my ($aggtries,$totaltries);
                   3113:         unless (exists($aggregates{$part})) {
1.270     albertel 3114: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3115: 
                   3116: 	    $aggtries = $totaltries;
1.269     raeburn  3117:             if ($$last_resets{$part}) {  
1.270     albertel 3118:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3119: 					   $part);
                   3120:             }
1.269     raeburn  3121:             $result.='<input type="hidden" name="'.
                   3122:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3123:             $result.='<input type="hidden" name="'.
                   3124:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3125:             $aggregates{$part} = 1;
                   3126:         }
1.41      ng       3127: 	if ($type eq 'awarded') {
1.320     albertel 3128: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3129: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3130: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3131: 	    $result.='<input type="text" name="'.
1.89      albertel 3132: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3133: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3134: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3135: 	} elsif ($type eq 'solved') {
                   3136: 	    my ($status,$foo)=split(/_/,$score,2);
                   3137: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3138: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3139: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3140: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3141: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3142: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3143: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3144: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3145: 	    $result.='<option>reset status</option>';
1.126     ng       3146: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3147: 	} else {
                   3148: 	    $result.='<input type="hidden" name="'.
                   3149: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3150: 		    "\n";
1.233     albertel 3151: 	    $result.='<input type="text" name="'.
1.122     ng       3152: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3153: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3154: 	}
                   3155:     }
                   3156:     $result.='</tr>';
                   3157:     return $result;
1.38      ng       3158: }
                   3159: 
1.44      ng       3160: #--- change scores for all the students in a section/class
                   3161: #    record does not get update if unchanged
1.38      ng       3162: sub editgrades {
1.41      ng       3163:     my ($request) = @_;
                   3164: 
1.324     albertel 3165:     my $symb=&get_symb($request);
1.398     albertel 3166:     my $title='<h3><span class="LC_info">Current Grade Status</span></h3>';
                   3167:     $title.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4><br />'."\n";
                   3168:     $title.='<h4><b>Section: </b>'.$env{'form.section'}.'</h4>'."\n";
1.126     ng       3169: 
1.44      ng       3170:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3171:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3172: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3173: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3174: 
                   3175:     my %scoreptr = (
                   3176: 		    'correct'  =>'correct_by_override',
                   3177: 		    'incorrect'=>'incorrect_by_override',
                   3178: 		    'excused'  =>'excused',
                   3179: 		    'ungraded' =>'ungraded_attempted',
                   3180: 		    'nothing'  => '',
                   3181: 		    );
1.257     albertel 3182:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3183: 
1.44      ng       3184:     my (@partid);
                   3185:     my %weight = ();
1.54      albertel 3186:     my %columns = ();
1.44      ng       3187:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3188: 
1.324     albertel 3189:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3190:     my $header;
1.257     albertel 3191:     while ($ctr < $env{'form.totalparts'}) {
                   3192: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3193: 	push @partid,$partid;
1.257     albertel 3194: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3195: 	$ctr++;
1.54      albertel 3196:     }
1.324     albertel 3197:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3198:     foreach my $partid (@partid) {
                   3199: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3200: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3201: 	$columns{$partid}=2;
                   3202: 	foreach my $stores (@parts) {
                   3203: 	    my ($part,$type) = &split_part_type($stores);
                   3204: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3205: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3206: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3207: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3208: 	    $display =~ s/Number of Attempts/Tries/;
                   3209: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3210: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3211: 	    $columns{$partid}+=2;
                   3212: 	}
                   3213:     }
                   3214:     foreach my $partid (@partid) {
1.324     albertel 3215: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3216: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3217: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3218: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3219: 
1.44      ng       3220:     }
                   3221:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3222:     $result .= $header;
1.44      ng       3223:     $result .= '</tr>'."\n";
1.93      albertel 3224:     my $noupdate;
1.126     ng       3225:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3226:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3227: 	my $line;
1.257     albertel 3228: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3229: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3230: 	my %newrecord;
                   3231: 	my $updateflag = 0;
1.281     albertel 3232: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3233: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3234: 	if (!&canmodify($usec)) {
1.126     ng       3235: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3236: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3237: 	    next;
                   3238: 	}
1.269     raeburn  3239:         my %aggregate = ();
                   3240:         my $aggregateflag = 0;
1.281     albertel 3241: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3242: 	foreach (@partid) {
1.257     albertel 3243: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3244: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3245: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3246: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3247: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3248: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3249: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3250: 	    my $score;
                   3251: 	    if ($partial eq '') {
1.257     albertel 3252: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3253: 	    } elsif ($partial > 0) {
                   3254: 		$score = 'correct_by_override';
                   3255: 	    } elsif ($partial == 0) {
                   3256: 		$score = 'incorrect_by_override';
                   3257: 	    }
1.257     albertel 3258: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3259: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3260: 
1.292     albertel 3261: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3262: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3263: 	    if ($dropMenu eq 'reset status' &&
                   3264: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3265: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3266: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3267: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3268: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3269: 		$updateflag = 1;
1.269     raeburn  3270:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3271:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3272:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3273:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3274:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3275:                     $aggregateflag = 1;
                   3276:                 }
1.139     albertel 3277: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3278: 		$updateflag = 1;
                   3279: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3280: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3281: 		$rec_update++;
1.125     ng       3282: 	    }
                   3283: 
1.93      albertel 3284: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3285: 		'<td align="center">'.$awarded.
                   3286: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3287: 
1.54      albertel 3288: 
                   3289: 	    my $partid=$_;
                   3290: 	    foreach my $stores (@parts) {
                   3291: 		my ($part,$type) = &split_part_type($stores);
                   3292: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3293: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3294: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3295: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3296: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3297: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3298: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3299: 		    $updateflag=1;
                   3300: 		}
1.93      albertel 3301: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3302: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3303: 	    }
1.44      ng       3304: 	}
1.93      albertel 3305: 	$line.='</tr>'."\n";
1.301     albertel 3306: 
                   3307: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3308: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3309: 
1.44      ng       3310: 	if ($updateflag) {
                   3311: 	    $count++;
1.257     albertel 3312: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3313: 				    $udom,$uname);
1.301     albertel 3314: 
                   3315: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3316: 					      $cnum,$udom,$uname)) {
                   3317: 		# need to figure out if should be in queue.
                   3318: 		my %record =  
                   3319: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3320: 					     $udom,$uname);
                   3321: 		my $all_graded = 1;
                   3322: 		my $none_graded = 1;
                   3323: 		foreach my $part (@parts) {
                   3324: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3325: 			$all_graded = 0;
                   3326: 		    } else {
                   3327: 			$none_graded = 0;
                   3328: 		    }
                   3329: 		}
                   3330: 
                   3331: 		if ($all_graded || $none_graded) {
                   3332: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3333: 							   $symb,$cdom,$cnum,
                   3334: 							   $udom,$uname);
                   3335: 		}
                   3336: 	    }
                   3337: 
1.126     ng       3338: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3339: 	    $updateCtr++;
1.93      albertel 3340: 	} else {
1.126     ng       3341: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3342: 	    $noupdateCtr++;
1.44      ng       3343: 	}
1.269     raeburn  3344:         if ($aggregateflag) {
                   3345:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3346: 				  $cdom,$cnum);
1.269     raeburn  3347:         }
1.93      albertel 3348:     }
                   3349:     if ($noupdate) {
1.126     ng       3350: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3351: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3352: 	$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       3353:     }
1.72      ng       3354:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3355: 	&show_grading_menu_form ($symb);
1.125     ng       3356:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3357: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3358: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3359:     return $title.$msg.$result;
1.5       albertel 3360: }
1.54      albertel 3361: 
                   3362: sub split_part_type {
                   3363:     my ($partstr) = @_;
                   3364:     my ($temp,@allparts)=split(/_/,$partstr);
                   3365:     my $type=pop(@allparts);
                   3366:     my $part=join('.',@allparts);
                   3367:     return ($part,$type);
                   3368: }
                   3369: 
1.44      ng       3370: #------------- end of section for handling grading by section/class ---------
                   3371: #
                   3372: #----------------------------------------------------------------------------
                   3373: 
1.5       albertel 3374: 
1.44      ng       3375: #----------------------------------------------------------------------------
                   3376: #
                   3377: #-------------------------- Next few routines handles grading by csv upload
                   3378: #
                   3379: #--- Javascript to handle csv upload
1.27      albertel 3380: sub csvupload_javascript_reverse_associate {
1.246     albertel 3381:     my $error1=&mt('You need to specify the username or ID');
                   3382:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3383:   return(<<ENDPICK);
                   3384:   function verify(vf) {
                   3385:     var foundsomething=0;
                   3386:     var founduname=0;
1.243     albertel 3387:     var foundID=0;
1.27      albertel 3388:     for (i=0;i<=vf.nfields.value;i++) {
                   3389:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3390:       if (i==0 && tw!=0) { foundID=1; }
                   3391:       if (i==1 && tw!=0) { founduname=1; }
                   3392:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3393:     }
1.246     albertel 3394:     if (founduname==0 && foundID==0) {
                   3395: 	alert('$error1');
                   3396: 	return;
1.27      albertel 3397:     }
                   3398:     if (foundsomething==0) {
1.246     albertel 3399: 	alert('$error2');
                   3400: 	return;
1.27      albertel 3401:     }
                   3402:     vf.submit();
                   3403:   }
                   3404:   function flip(vf,tf) {
                   3405:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3406:     var i;
                   3407:     for (i=0;i<=vf.nfields.value;i++) {
                   3408:       //can not pick the same destination field for both name and domain
                   3409:       if (((i ==0)||(i ==1)) && 
                   3410:           ((tf==0)||(tf==1)) && 
                   3411:           (i!=tf) &&
                   3412:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3413:         eval('vf.f'+i+'.selectedIndex=0;')
                   3414:       }
                   3415:     }
                   3416:   }
                   3417: ENDPICK
                   3418: }
                   3419: 
                   3420: sub csvupload_javascript_forward_associate {
1.246     albertel 3421:     my $error1=&mt('You need to specify the username or ID');
                   3422:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3423:   return(<<ENDPICK);
                   3424:   function verify(vf) {
                   3425:     var foundsomething=0;
                   3426:     var founduname=0;
1.243     albertel 3427:     var foundID=0;
1.27      albertel 3428:     for (i=0;i<=vf.nfields.value;i++) {
                   3429:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3430:       if (tw==1) { foundID=1; }
                   3431:       if (tw==2) { founduname=1; }
                   3432:       if (tw>3) { foundsomething=1; }
1.27      albertel 3433:     }
1.246     albertel 3434:     if (founduname==0 && foundID==0) {
                   3435: 	alert('$error1');
                   3436: 	return;
1.27      albertel 3437:     }
                   3438:     if (foundsomething==0) {
1.246     albertel 3439: 	alert('$error2');
                   3440: 	return;
1.27      albertel 3441:     }
                   3442:     vf.submit();
                   3443:   }
                   3444:   function flip(vf,tf) {
                   3445:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3446:     var i;
                   3447:     //can not pick the same destination field twice
                   3448:     for (i=0;i<=vf.nfields.value;i++) {
                   3449:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3450:         eval('vf.f'+i+'.selectedIndex=0;')
                   3451:       }
                   3452:     }
                   3453:   }
                   3454: ENDPICK
                   3455: }
                   3456: 
1.26      albertel 3457: sub csvuploadmap_header {
1.324     albertel 3458:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3459:     my $javascript;
1.257     albertel 3460:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3461: 	$javascript=&csvupload_javascript_reverse_associate();
                   3462:     } else {
                   3463: 	$javascript=&csvupload_javascript_forward_associate();
                   3464:     }
1.45      ng       3465: 
1.324     albertel 3466:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3467:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3468:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3469:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3470:     $request->print(<<ENDPICK);
1.26      albertel 3471: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3472: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3473: $result
1.326     albertel 3474: <hr />
1.26      albertel 3475: <h3>Identify fields</h3>
                   3476: Total number of records found in file: $distotal <hr />
                   3477: Enter as many fields as you can. The system will inform you and bring you back
                   3478: to this page if the data selected is insufficient to run your class.<hr />
                   3479: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3480: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3481: <input type="hidden" name="associate"  value="" />
                   3482: <input type="hidden" name="phase"      value="three" />
                   3483: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3484: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3485: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3486: <input type="hidden" name="upfile_associate" 
1.257     albertel 3487:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3488: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3489: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3490: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3491: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3492: <hr />
                   3493: <script type="text/javascript" language="Javascript">
                   3494: $javascript
                   3495: </script>
                   3496: ENDPICK
1.118     ng       3497:     return '';
1.26      albertel 3498: 
                   3499: }
                   3500: 
                   3501: sub csvupload_fields {
1.324     albertel 3502:     my ($symb) = @_;
                   3503:     my (@parts) = &getpartlist($symb);
1.243     albertel 3504:     my @fields=(['ID','Student ID'],
                   3505: 		['username','Student Username'],
                   3506: 		['domain','Student Domain']);
1.324     albertel 3507:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3508:     foreach my $part (sort(@parts)) {
                   3509: 	my @datum;
                   3510: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3511: 	my $name=$part;
                   3512: 	if  (!$display) { $display = $name; }
                   3513: 	@datum=($name,$display);
1.244     albertel 3514: 	if ($name=~/^stores_(.*)_awarded/) {
                   3515: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3516: 	}
1.41      ng       3517: 	push(@fields,\@datum);
                   3518:     }
                   3519:     return (@fields);
1.26      albertel 3520: }
                   3521: 
                   3522: sub csvuploadmap_footer {
1.41      ng       3523:     my ($request,$i,$keyfields) =@_;
                   3524:     $request->print(<<ENDPICK);
1.26      albertel 3525: </table>
                   3526: <input type="hidden" name="nfields" value="$i" />
                   3527: <input type="hidden" name="keyfields" value="$keyfields" />
                   3528: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3529: </form>
                   3530: ENDPICK
                   3531: }
                   3532: 
1.283     albertel 3533: sub checkforfile_js {
1.86      ng       3534:     my $result =<<CSVFORMJS;
                   3535: <script type="text/javascript" language="javascript">
                   3536:     function checkUpload(formname) {
                   3537: 	if (formname.upfile.value == "") {
                   3538: 	    alert("Please use the browse button to select a file from your local directory.");
                   3539: 	    return false;
                   3540: 	}
                   3541: 	formname.submit();
                   3542:     }
                   3543:     </script>
                   3544: CSVFORMJS
1.283     albertel 3545:     return $result;
                   3546: }
                   3547: 
                   3548: sub upcsvScores_form {
                   3549:     my ($request) = shift;
1.324     albertel 3550:     my ($symb)=&get_symb($request);
1.283     albertel 3551:     if (!$symb) {return '';}
                   3552:     my $result=&checkforfile_js();
1.257     albertel 3553:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3554:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3555:     $result.=$table;
1.326     albertel 3556:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3557:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3558:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3559: 	'.</b></td></tr>'."\n";
                   3560:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3561:     my $upload=&mt("Upload Scores");
1.86      ng       3562:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3563:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3564:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3565:     $result.=<<ENDUPFORM;
1.106     albertel 3566: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3567: <input type="hidden" name="symb" value="$symb" />
                   3568: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3569: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3570: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3571: $upfile_select
1.370     www      3572: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3573: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3574: </form>
                   3575: ENDUPFORM
1.370     www      3576:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3577:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3578:     .'</td></tr></table>'."\n";
1.86      ng       3579:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3580:     $result.=&show_grading_menu_form($symb);
1.86      ng       3581:     return $result;
                   3582: }
                   3583: 
                   3584: 
1.26      albertel 3585: sub csvuploadmap {
1.41      ng       3586:     my ($request)= @_;
1.324     albertel 3587:     my ($symb)=&get_symb($request);
1.41      ng       3588:     if (!$symb) {return '';}
1.72      ng       3589: 
1.41      ng       3590:     my $datatoken;
1.257     albertel 3591:     if (!$env{'form.datatoken'}) {
1.41      ng       3592: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3593:     } else {
1.257     albertel 3594: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3595: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3596:     }
1.41      ng       3597:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3598:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3599:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3600:     my ($i,$keyfields);
                   3601:     if (@records) {
1.324     albertel 3602: 	my @fields=&csvupload_fields($symb);
1.45      ng       3603: 
1.257     albertel 3604: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3605: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3606: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3607: 							  \@fields);
                   3608: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3609: 	    chop($keyfields);
                   3610: 	} else {
                   3611: 	    unshift(@fields,['none','']);
                   3612: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3613: 							    \@fields);
1.311     banghart 3614:             foreach my $rec (@records) {
                   3615:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3616:                 if (%temp) {
                   3617:                     $keyfields=join(',',sort(keys(%temp)));
                   3618:                     last;
                   3619:                 }
                   3620:             }
1.41      ng       3621: 	}
                   3622:     }
                   3623:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3624:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3625: 
1.41      ng       3626:     return '';
1.27      albertel 3627: }
                   3628: 
1.246     albertel 3629: sub csvuploadoptions {
1.41      ng       3630:     my ($request)= @_;
1.324     albertel 3631:     my ($symb)=&get_symb($request);
1.257     albertel 3632:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3633:     my $ignore=&mt('Ignore First Line');
                   3634:     $request->print(<<ENDPICK);
                   3635: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3636: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3637: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3638: <!--
1.246     albertel 3639: <p>
                   3640: <label>
                   3641:    <input type="checkbox" name="show_full_results" />
                   3642:    Show a table of all changes
                   3643: </label>
                   3644: </p>
1.302     albertel 3645: -->
1.246     albertel 3646: <p>
                   3647: <label>
                   3648:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3649:    Overwrite any existing score
                   3650: </label>
                   3651: </p>
                   3652: ENDPICK
                   3653:     my %fields=&get_fields();
                   3654:     if (!defined($fields{'domain'})) {
1.257     albertel 3655: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3656: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3657:     }
1.257     albertel 3658:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3659: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3660: 	my $cleankey=$1;
                   3661: 	if ($cleankey eq 'command') { next; }
                   3662: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3663: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3664:     }
                   3665:     # FIXME do a check for any duplicated user ids...
                   3666:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3667:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3668: <hr /></form>'."\n");
1.324     albertel 3669:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3670:     return '';
                   3671: }
                   3672: 
                   3673: sub get_fields {
                   3674:     my %fields;
1.257     albertel 3675:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3676:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3677: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3678: 	    if ($env{'form.f'.$i} ne 'none') {
                   3679: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3680: 	    }
                   3681: 	} else {
1.257     albertel 3682: 	    if ($env{'form.f'.$i} ne 'none') {
                   3683: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3684: 	    }
                   3685: 	}
1.27      albertel 3686:     }
1.246     albertel 3687:     return %fields;
                   3688: }
                   3689: 
                   3690: sub csvuploadassign {
                   3691:     my ($request)= @_;
1.324     albertel 3692:     my ($symb)=&get_symb($request);
1.246     albertel 3693:     if (!$symb) {return '';}
1.345     bowersj2 3694:     my $error_msg = '';
1.246     albertel 3695:     &Apache::loncommon::load_tmp_file($request);
                   3696:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3697:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3698:     my %fields=&get_fields();
1.41      ng       3699:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3700:     my $courseid=$env{'request.course.id'};
1.97      albertel 3701:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3702:     my @notallowed;
1.41      ng       3703:     my @skipped;
                   3704:     my $countdone=0;
                   3705:     foreach my $grade (@gradedata) {
                   3706: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3707: 	my $domain;
                   3708: 	if ($entries{$fields{'domain'}}) {
                   3709: 	    $domain=$entries{$fields{'domain'}};
                   3710: 	} else {
1.257     albertel 3711: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3712: 	}
1.243     albertel 3713: 	$domain=~s/\s//g;
1.41      ng       3714: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3715: 	$username=~s/\s//g;
1.243     albertel 3716: 	if (!$username) {
                   3717: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3718: 	    $id=~s/\s//g;
1.243     albertel 3719: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3720: 	    $username=$ids{$id};
                   3721: 	}
1.41      ng       3722: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3723: 	    my $id=$entries{$fields{'ID'}};
                   3724: 	    $id=~s/\s//g;
                   3725: 	    if ($id) {
                   3726: 		push(@skipped,"$id:$domain");
                   3727: 	    } else {
                   3728: 		push(@skipped,"$username:$domain");
                   3729: 	    }
1.41      ng       3730: 	    next;
                   3731: 	}
1.108     albertel 3732: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3733: 	if (!&canmodify($usec)) {
                   3734: 	    push(@notallowed,"$username:$domain");
                   3735: 	    next;
                   3736: 	}
1.244     albertel 3737: 	my %points;
1.41      ng       3738: 	my %grades;
                   3739: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3740: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3741: 		$dest eq 'domain') { next; }
                   3742: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3743: 	    if ($dest=~/stores_(.*)_points/) {
                   3744: 		my $part=$1;
                   3745: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3746: 					      $symb,$domain,$username);
1.345     bowersj2 3747:                 if ($wgt) {
                   3748:                     $entries{$fields{$dest}}=~s/\s//g;
                   3749:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3750:                     my $award='correct_by_override';
                   3751:                     $grades{"resource.$part.awarded"}=$pcr;
                   3752:                     $grades{"resource.$part.solved"}=$award;
                   3753:                     $points{$part}=1;
                   3754:                 } else {
                   3755:                     $error_msg = "<br />" .
                   3756:                         &mt("Some point values were assigned"
                   3757:                             ." for problems with a weight "
                   3758:                             ."of zero. These values were "
                   3759:                             ."ignored.");
                   3760:                 }
1.244     albertel 3761: 	    } else {
                   3762: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3763: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3764: 		my $store_key=$dest;
                   3765: 		$store_key=~s/^stores/resource/;
                   3766: 		$store_key=~s/_/\./g;
                   3767: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3768: 	    }
1.41      ng       3769: 	}
1.398     albertel 3770: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3771: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.244     albertel 3772: #	&Apache::lonnet::logthis(" storing ".(join('-',%grades)));
1.302     albertel 3773: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3774: 					   $env{'request.course.id'},
                   3775: 					   $domain,$username);
                   3776: 	if ($result eq 'ok') {
                   3777: 	    $request->print('.');
                   3778: 	} else {
                   3779: 	    $request->print("<p>
1.398     albertel 3780:                               <span class=\"LC_error\">
                   3781:                                  Failed to save student $username:$domain.
                   3782:                                  Message when trying to save was ($result)
                   3783:                               </span>
1.302     albertel 3784:                              </p>" );
                   3785: 	}
1.41      ng       3786: 	$request->rflush();
                   3787: 	$countdone++;
                   3788:     }
1.398     albertel 3789:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3790:     if (@skipped) {
1.398     albertel 3791: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3792: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3793:     }
                   3794:     if (@notallowed) {
1.398     albertel 3795: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3796: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3797:     }
1.106     albertel 3798:     $request->print("<br />\n");
1.324     albertel 3799:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3800:     return $error_msg;
1.26      albertel 3801: }
1.44      ng       3802: #------------- end of section for handling csv file upload ---------
                   3803: #
                   3804: #-------------------------------------------------------------------
                   3805: #
1.122     ng       3806: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3807: #
                   3808: #--- Select a page/sequence and a student to grade
1.68      ng       3809: sub pickStudentPage {
                   3810:     my ($request) = shift;
                   3811: 
                   3812:     $request->print(<<LISTJAVASCRIPT);
                   3813: <script type="text/javascript" language="javascript">
                   3814: 
                   3815: function checkPickOne(formname) {
1.76      ng       3816:     if (radioSelection(formname.student) == null) {
1.68      ng       3817: 	alert("Please select the student you wish to grade.");
                   3818: 	return;
                   3819:     }
1.125     ng       3820:     ptr = pullDownSelection(formname.selectpage);
                   3821:     formname.page.value = formname["page"+ptr].value;
                   3822:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3823:     formname.submit();
                   3824: }
                   3825: 
                   3826: </script>
                   3827: LISTJAVASCRIPT
1.118     ng       3828:     &commonJSfunctions($request);
1.324     albertel 3829:     my ($symb) = &get_symb($request);
1.257     albertel 3830:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3831:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3832:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3833: 
1.398     albertel 3834:     my $result='<h3><span class="LC_info">&nbsp;'.
                   3835: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       3836: 
1.80      ng       3837:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3838:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 3839:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 3840:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3841: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3842: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3843:     my $ctr=0;
1.68      ng       3844:     foreach (@$titles) {
                   3845: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3846: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 3847: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       3848: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3849: 	$ctr++;
1.68      ng       3850:     }
1.326     albertel 3851:     $result.= '</select>'."<br />\n";
1.70      ng       3852:     $ctr=0;
                   3853:     foreach (@$titles) {
                   3854: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3855: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3856: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3857: 	$ctr++;
                   3858:     }
1.72      ng       3859:     $result.='<input type="hidden" name="page" />'."\n".
                   3860: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3861: 
1.401     albertel 3862:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 3863: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       3864: 
1.71      ng       3865:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 3866: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 3867: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 3868: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.72      ng       3869: 
1.68      ng       3870:     $result.='<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
1.257     albertel 3871: 	'<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.72      ng       3872: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 3873: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 3874: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       3875: 
1.382     albertel 3876:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   3877: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   3878: 
1.80      ng       3879:     $result.='&nbsp;<input type="button" '.
1.126     ng       3880: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       3881: 
1.68      ng       3882:     $request->print($result);
                   3883: 
1.326     albertel 3884:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       3885: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3886: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       3887: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3888: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       3889: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3890: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       3891:  
1.76      ng       3892:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       3893:     my $ptr = 1;
1.294     albertel 3894:     foreach my $student (sort 
                   3895: 			 {
                   3896: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3897: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3898: 			     }
                   3899: 			     return $a cmp $b;
                   3900: 			 } (keys(%$fullname))) {
1.68      ng       3901: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       3902: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   3903: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 3904: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   3905: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       3906: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       3907: 	$ptr++;
                   3908:     }
1.381     albertel 3909:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   3910:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       3911:     $studentTable.='<input type="button" '.
                   3912: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       3913: 
1.324     albertel 3914:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       3915:     $request->print($studentTable);
                   3916: 
                   3917:     return '';
                   3918: }
                   3919: 
                   3920: sub getSymbMap {
1.132     bowersj2 3921:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       3922: 
                   3923:     my %symbx = ();
                   3924:     my @titles = ();
1.117     bowersj2 3925:     my $minder = 0;
                   3926: 
                   3927:     # Gather every sequence that has problems.
1.240     albertel 3928:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   3929: 					       1,0,1);
1.117     bowersj2 3930:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 3931: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 3932: 	    my $title = $minder.'.'.
                   3933: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   3934: 	    push(@titles, $title); # minder in case two titles are identical
                   3935: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 3936: 	    $minder++;
1.241     albertel 3937: 	}
1.68      ng       3938:     }
                   3939:     return \@titles,\%symbx;
                   3940: }
                   3941: 
1.72      ng       3942: #
                   3943: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       3944: sub displayPage {
                   3945:     my ($request) = shift;
                   3946: 
1.324     albertel 3947:     my ($symb) = &get_symb($request);
1.257     albertel 3948:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3949:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3950:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3951:     my $pageTitle = $env{'form.page'};
1.103     albertel 3952:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 3953:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   3954:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 3955: 
                   3956:     #need to make sure we have the correct data for later EXT calls, 
                   3957:     #thus invalidate the cache
                   3958:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3959:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3960:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3961:     &Apache::lonnet::clear_EXT_cache_status();
                   3962: 
1.103     albertel 3963:     if (!&canview($usec)) {
1.398     albertel 3964: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 3965: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 3966: 	return;
                   3967:     }
1.398     albertel 3968:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 3969:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       3970: 	'</h3>'."\n";
1.382     albertel 3971:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   3972: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   3973:     } else {
                   3974: 	delete($env{'form.CODE'});
                   3975:     }
1.71      ng       3976:     &sub_page_js($request);
                   3977:     $request->print($result);
                   3978: 
1.132     bowersj2 3979:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 3980:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       3981:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 3982:     if (!$map) {
1.398     albertel 3983: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 3984: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 3985: 	return; 
                   3986:     }
1.68      ng       3987:     my $iterator = $navmap->getIterator($map->map_start(),
                   3988: 					$map->map_finish());
                   3989: 
1.71      ng       3990:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       3991: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 3992: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   3993: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       3994: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 3995: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 3996: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       3997: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 3998: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       3999: 
1.382     albertel 4000:     if (defined($env{'form.CODE'})) {
                   4001: 	$studentTable.=
                   4002: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4003:     }
1.381     albertel 4004:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4005: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4006: 	'/check.gif" height="16" border="0" />';
                   4007: 
1.118     ng       4008:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4009: 	' symbol.'."\n".
1.71      ng       4010: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4011: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4012: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4013: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4014: 
1.329     albertel 4015:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4016:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4017:     $iterator->next(); # skip the first BEGIN_MAP
                   4018:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4019:     while ($depth > 0) {
1.68      ng       4020:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4021:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4022: 
1.385     albertel 4023:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4024: 	    my $parts = $curRes->parts();
1.68      ng       4025:             my $title = $curRes->compTitle();
1.71      ng       4026: 	    my $symbx = $curRes->symb();
1.196     albertel 4027: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4028: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4029: 	    $studentTable.='<td valign="top">';
1.382     albertel 4030: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4031: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4032: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4033: 					     undef,'both',\%form);
1.71      ng       4034: 	    } else {
1.382     albertel 4035: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4036: 		$companswer =~ s|<form(.*?)>||g;
                   4037: 		$companswer =~ s|</form>||g;
1.71      ng       4038: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4039: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4040: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4041: #		}
1.116     ng       4042: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4043: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4044: 	    }
                   4045: 
1.257     albertel 4046: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4047: 
1.257     albertel 4048: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4049: 		if ($record{'version'} eq '') {
1.398     albertel 4050: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4051: 		} else {
1.116     ng       4052: 		    my %responseType = ();
                   4053: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4054: 			my @responseIds =$curRes->responseIds($partid);
                   4055: 			my @responseType =$curRes->responseType($partid);
                   4056: 			my %responseIds;
                   4057: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4058: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4059: 			}
                   4060: 			$responseType{$partid} = \%responseIds;
1.116     ng       4061: 		    }
1.148     albertel 4062: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4063: 
1.71      ng       4064: 		}
1.257     albertel 4065: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4066: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4067: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4068: 									$env{'request.course.id'},
1.71      ng       4069: 									'','.submission');
                   4070:  
                   4071: 	    }
1.103     albertel 4072: 	    if (&canmodify($usec)) {
                   4073: 		foreach my $partid (@{$parts}) {
                   4074: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4075: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4076: 		    $question++;
                   4077: 		}
1.196     albertel 4078: 		$prob++;
1.71      ng       4079: 	    }
                   4080: 	    $studentTable.='</td></tr>';
1.68      ng       4081: 
1.103     albertel 4082: 	}
1.68      ng       4083:         $curRes = $iterator->next();
                   4084:     }
                   4085: 
1.381     albertel 4086:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4087: 	'<input type="button" value="Save" '.
1.381     albertel 4088: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4089: 	'</form>'."\n";
1.324     albertel 4090:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4091:     $request->print($studentTable);
                   4092: 
                   4093:     return '';
1.119     ng       4094: }
                   4095: 
                   4096: sub displaySubByDates {
1.148     albertel 4097:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4098:     my $isCODE=0;
1.335     albertel 4099:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4100:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4101:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4102: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4103: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4104: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4105: 	'<td><b>Submission</b></td>'.
                   4106: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4107:     my ($version);
                   4108:     my %mark;
1.148     albertel 4109:     my %orders;
1.119     ng       4110:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4111:     if (!exists($$record{'1:timestamp'})) {
1.398     albertel 4112: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
1.147     albertel 4113:     }
1.335     albertel 4114: 
                   4115:     my $interaction;
1.119     ng       4116:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4117: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4118: 	if (exists($$record{$version.':resource.0.version'})) {
                   4119: 	    $interaction = $$record{$version.':resource.0.version'};
                   4120: 	}
                   4121: 
                   4122: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4123: 		             : "$version:resource");
                   4124: 	#&Apache::lonnet::logthis(" got $where");
1.119     ng       4125: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4126: 	if ($isCODE) {
                   4127: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4128: 	}
1.119     ng       4129: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4130: 	my @displaySub = ();
                   4131: 	foreach my $partid (@{$parts}) {
1.335     albertel 4132: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4133: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4134: 	    
                   4135: 
1.122     ng       4136: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4137: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4138: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4139: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4140: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4141: 
                   4142: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4143: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   4144: 		    #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
1.207     albertel 4145: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.398     albertel 4146: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
                   4147: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4148: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4149: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4150: 		    } else {
                   4151: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4152: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4153: 		    }
1.335     albertel 4154: 		    my $responseType=($isTask ? 'Task'
                   4155:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4156: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4157: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4158: 			$orders{$partid}->{$responseId}=
                   4159: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4160: 		    }
1.147     albertel 4161: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4162: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4163: 		}
                   4164: 	    }
1.335     albertel 4165: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4166: 		$displaySub[1].='Checked in by '.
                   4167: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4168: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4169: 		    '<br />';
                   4170: 	    }
                   4171: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4172: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4173: 		    lc($$record{"$where.$partid.award"}).' '.
                   4174: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4175: 		    '<br />';
                   4176: 	    }
1.335     albertel 4177: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4178: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4179: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4180: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4181: 		$displaySub[2].=
                   4182: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4183: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4184: 	    }
                   4185: 	}
                   4186: 	# needed because old essay regrader has not parts info
                   4187: 	if (exists $$record{"$version:resource.regrader"}) {
                   4188: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4189: 	}
                   4190: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4191: 	if ($displaySub[2]) {
                   4192: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4193: 	}
1.382     albertel 4194: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4195:     
1.119     ng       4196:     }
                   4197:     $studentTable.='</table></td></tr></table>';
                   4198:     return $studentTable;
1.71      ng       4199: }
                   4200: 
                   4201: sub updateGradeByPage {
                   4202:     my ($request) = shift;
                   4203: 
1.257     albertel 4204:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4205:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4206:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4207:     my $pageTitle = $env{'form.page'};
1.103     albertel 4208:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4209:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4210:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4211:     if (!&canmodify($usec)) {
1.398     albertel 4212: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4213: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4214: 	return;
                   4215:     }
1.398     albertel 4216:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4217:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4218: 	'</h3>'."\n";
1.70      ng       4219: 
1.68      ng       4220:     $request->print($result);
                   4221: 
1.132     bowersj2 4222:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4223:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4224:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4225:     if (!$map) {
1.398     albertel 4226: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4227: 	my ($symb)=&get_symb($request);
                   4228: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4229: 	return; 
                   4230:     }
1.71      ng       4231:     my $iterator = $navmap->getIterator($map->map_start(),
                   4232: 					$map->map_finish());
1.70      ng       4233: 
1.71      ng       4234:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4235: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4236: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4237: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4238: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4239: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4240: 
                   4241:     $iterator->next(); # skip the first BEGIN_MAP
                   4242:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4243:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4244:     while ($depth > 0) {
1.71      ng       4245:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4246:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4247: 
1.385     albertel 4248:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4249: 	    my $parts = $curRes->parts();
1.71      ng       4250:             my $title = $curRes->compTitle();
                   4251: 	    my $symbx = $curRes->symb();
1.196     albertel 4252: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4253: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4254: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4255: 
                   4256: 	    my %newrecord=();
                   4257: 	    my @displayPts=();
1.269     raeburn  4258:             my %aggregate = ();
                   4259:             my $aggregateflag = 0;
1.71      ng       4260: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4261: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4262: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4263: 
1.257     albertel 4264: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4265: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4266: 		my $partial = $newpts/$wgt;
                   4267: 		my $score;
                   4268: 		if ($partial > 0) {
                   4269: 		    $score = 'correct_by_override';
1.125     ng       4270: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4271: 		    $score = 'incorrect_by_override';
                   4272: 		}
1.257     albertel 4273: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4274: 		if ($dropMenu eq 'excused') {
1.71      ng       4275: 		    $partial = '';
                   4276: 		    $score = 'excused';
1.125     ng       4277: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4278: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4279: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4280: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4281: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4282: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4283: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4284: 		    $changeflag++;
                   4285: 		    $newpts = '';
1.269     raeburn  4286:                     
                   4287:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4288:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4289:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4290:                     if ($aggtries > 0) {
                   4291:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4292:                         $aggregateflag = 1;
                   4293:                     }
1.71      ng       4294: 		}
1.324     albertel 4295: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4296: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4297: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4298: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4299: 		    '&nbsp;<br />';
1.207     albertel 4300: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4301: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4302: 		    '&nbsp;<br />';
1.71      ng       4303: 		$question++;
1.380     albertel 4304: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4305: 
1.71      ng       4306: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4307: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4308: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4309: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4310: 
                   4311: 		$changeflag++;
                   4312: 	    }
                   4313: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4314: 		my %record = 
                   4315: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4316: 					     $udom,$uname);
                   4317: 
                   4318: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4319: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4320: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4321: 		    $newrecord{'resource.CODE'} = '';
                   4322: 		}
1.257     albertel 4323: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4324: 					$udom,$uname);
1.382     albertel 4325: 		%record = &Apache::lonnet::restore($symbx,
                   4326: 						   $env{'request.course.id'},
                   4327: 						   $udom,$uname);
1.380     albertel 4328: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4329: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4330: 	    }
1.380     albertel 4331: 	    
1.269     raeburn  4332:             if ($aggregateflag) {
                   4333:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4334:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4335:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4336:             }
1.125     ng       4337: 
1.71      ng       4338: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4339: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4340: 		'</tr>';
1.68      ng       4341: 
1.196     albertel 4342: 	    $prob++;
1.68      ng       4343: 	}
1.71      ng       4344:         $curRes = $iterator->next();
1.68      ng       4345:     }
1.98      albertel 4346: 
1.71      ng       4347:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4348:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4349:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4350: 		  'The scores were changed for '.
                   4351: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4352:     $request->print($grademsg.$studentTable);
1.68      ng       4353: 
1.70      ng       4354:     return '';
                   4355: }
                   4356: 
1.72      ng       4357: #-------- end of section for handling grading by page/sequence ---------
                   4358: #
                   4359: #-------------------------------------------------------------------
                   4360: 
1.75      albertel 4361: #--------------------Scantron Grading-----------------------------------
                   4362: #
                   4363: #------ start of section for handling grading by page/sequence ---------
                   4364: 
1.423     albertel 4365: =pod
                   4366: 
                   4367: =head1 Bubble sheet grading routines
                   4368: 
1.424     albertel 4369:   For this documentation:
                   4370: 
                   4371:    'scanline' refers to the full line of characters
                   4372:    from the file that we are parsing that represents one entire sheet
                   4373: 
                   4374:    'bubble line' refers to the data
                   4375:    representing the line of bubbles that are on the physical bubble sheet
                   4376: 
                   4377: 
                   4378: The overall process is that a scanned in bubble sheet data is uploaded
                   4379: into a course. When a user wants to grade, they select a
                   4380: sequence/folder of resources, a file of bubble sheet info, and pick
                   4381: one of the predefined configurations for what each scanline looks
                   4382: like.
                   4383: 
                   4384: Next each scanline is checked for any errors of either 'missing
                   4385: bubbles' (it's an error because it may have been missed scanned
                   4386: because too light bubbling), 'double bubble' (each bubble line should
                   4387: have no more that one letter picked), invalid or duplicated CODE,
                   4388: invalid student ID
                   4389: 
                   4390: If the CODE option is used that determines the randomization of the
                   4391: homework problems, either way the student ID is looked up into a
                   4392: username:domain.
                   4393: 
                   4394: During the validation phase the instructor can choose to skip scanlines. 
                   4395: 
                   4396: After the validation phase, there is now 3 bubble sheet files
                   4397: 
                   4398:   scantron_original_filename (unmodified original file)
                   4399:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4400:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4401: 
                   4402: Also there is a separate hash nohist_scantrondata that contains extra
                   4403: correction information that isn't representable in the bubble sheet
                   4404: file (see &scantron_getfile() for more information)
                   4405: 
                   4406: After all scanlines are either valid, marked as valid or skipped, then
                   4407: foreach line foreach problem in the picked sequence, an ssi request is
                   4408: made that simulates a user submitting their selected letter(s) against
                   4409: the homework problem.
1.423     albertel 4410: 
                   4411: =over 4
                   4412: 
                   4413: =cut
                   4414: 
                   4415: 
                   4416: =pod 
                   4417: 
                   4418: =item defaultFormData
                   4419: 
                   4420:   Returns html hidden inputs used to hold context/default values.
                   4421: 
                   4422:  Arguments:
                   4423:   $symb - $symb of the current resource 
                   4424: 
                   4425: =cut
1.422     foxr     4426: 
1.81      albertel 4427: sub defaultFormData {
1.324     albertel 4428:     my ($symb)=@_;
1.81      albertel 4429:     return '
1.418     albertel 4430:       <input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4431:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4432:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4433: }
                   4434: 
1.423     albertel 4435: =pod 
                   4436: 
                   4437: =item getSequenceDropDown
                   4438: 
                   4439:    Return html dropdown of possible sequences to grade
                   4440:  
                   4441:  Arguments:
                   4442:    $symb - $symb of the current resource 
                   4443: 
                   4444: =cut
1.422     foxr     4445: 
1.75      albertel 4446: sub getSequenceDropDown {
1.423     albertel 4447:     my ($symb)=@_;
1.75      albertel 4448:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4449:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4450:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4451:     my $ctr=0;
                   4452:     foreach (@$titles) {
                   4453: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4454: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4455: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4456: 	    '>'.$showtitle.'</option>'."\n";
                   4457: 	$ctr++;
                   4458:     }
                   4459:     $result.= '</select>';
                   4460:     return $result;
                   4461: }
                   4462: 
1.423     albertel 4463: 
                   4464: =pod 
                   4465: 
                   4466: =item scantron_filenames
                   4467: 
                   4468:    Returns a list of the scantron files in the current course 
                   4469: 
                   4470: =cut
1.422     foxr     4471: 
1.202     albertel 4472: sub scantron_filenames {
1.257     albertel 4473:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4474:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4475:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4476: 				    &propath($cdom,$cname));
1.202     albertel 4477:     my @possiblenames;
1.201     albertel 4478:     foreach my $filename (sort(@files)) {
1.157     albertel 4479: 	($filename)=split(/&/,$filename);
                   4480: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4481: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4482: 	push(@possiblenames,$filename);
                   4483:     }
                   4484:     return @possiblenames;
                   4485: }
                   4486: 
1.423     albertel 4487: =pod 
                   4488: 
                   4489: =item scantron_uploads
                   4490: 
                   4491:    Returns  html drop-down list of scantron files in current course.
                   4492: 
                   4493:  Arguments:
                   4494:    $file2grade - filename to set as selected in the dropdown
                   4495: 
                   4496: =cut
1.422     foxr     4497: 
1.202     albertel 4498: sub scantron_uploads {
1.209     ng       4499:     my ($file2grade) = @_;
1.202     albertel 4500:     my $result=	'<select name="scantron_selectfile">';
                   4501:     $result.="<option></option>";
                   4502:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4503: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4504:     }
                   4505:     $result.="</select>";
                   4506:     return $result;
                   4507: }
                   4508: 
1.423     albertel 4509: =pod 
                   4510: 
                   4511: =item scantron_scantab
                   4512: 
                   4513:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4514:   file.
                   4515: 
                   4516: =cut
1.422     foxr     4517: 
1.82      albertel 4518: sub scantron_scantab {
                   4519:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4520:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4521:     $result.='<option></option>'."\n";
1.82      albertel 4522:     foreach my $line (<$fh>) {
                   4523: 	my ($name,$descrip)=split(/:/,$line);
                   4524: 	if ($name =~ /^\#/) { next; }
                   4525: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4526:     }
                   4527:     $result.='</select>'."\n";
                   4528: 
                   4529:     return $result;
                   4530: }
                   4531: 
1.423     albertel 4532: =pod 
                   4533: 
                   4534: =item scantron_CODElist
                   4535: 
                   4536:   Returns html drop down of the saved CODE lists from current course,
                   4537:   generated from earlier printings.
                   4538: 
                   4539: =cut
1.422     foxr     4540: 
1.186     albertel 4541: sub scantron_CODElist {
1.257     albertel 4542:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4543:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4544:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4545:     my $namechoice='<option></option>';
1.225     albertel 4546:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4547: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4548: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4549: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4550:     }
                   4551:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4552:     return $namechoice;
                   4553: }
                   4554: 
1.423     albertel 4555: =pod 
                   4556: 
                   4557: =item scantron_CODEunique
                   4558: 
                   4559:   Returns the html for "Each CODE to be used once" radio.
                   4560: 
                   4561: =cut
1.422     foxr     4562: 
1.186     albertel 4563: sub scantron_CODEunique {
1.381     albertel 4564:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4565:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4566:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4567:                 </span>
                   4568:                 <span style="white-space: nowrap;">
1.272     albertel 4569:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4570:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4571:                 </span>';
1.186     albertel 4572:     return $result;
                   4573: }
1.423     albertel 4574: 
                   4575: =pod 
                   4576: 
                   4577: =item scantron_selectphase
                   4578: 
                   4579:   Generates the initial screen to start the bubble sheet process.
                   4580:   Allows for - starting a grading run.
1.424     albertel 4581:              - downloading existing scan data (original, corrected
1.423     albertel 4582:                                                 or skipped info)
                   4583: 
                   4584:              - uploading new scan data
                   4585: 
                   4586:  Arguments:
                   4587:   $r          - The Apache request object
                   4588:   $file2grade - name of the file that contain the scanned data to score
                   4589: 
                   4590: =cut
1.186     albertel 4591: 
1.75      albertel 4592: sub scantron_selectphase {
1.209     ng       4593:     my ($r,$file2grade) = @_;
1.324     albertel 4594:     my ($symb)=&get_symb($r);
1.75      albertel 4595:     if (!$symb) {return '';}
1.423     albertel 4596:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4597:     my $default_form_data=&defaultFormData($symb);
                   4598:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4599:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4600:     my $format_selector=&scantron_scantab();
1.186     albertel 4601:     my $CODE_selector=&scantron_CODElist();
                   4602:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4603:     my $result;
1.422     foxr     4604: 
                   4605:     # Chunk of form to prompt for a file to grade and how:
                   4606: 
1.75      albertel 4607:     $result.= <<SCANTRONFORM;
1.162     albertel 4608:     <table width="100%" border="0">
1.75      albertel 4609:     <tr>
1.226     albertel 4610:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4611:       <td bgcolor="#777777">
1.203     albertel 4612:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4613:         $default_form_data
1.75      albertel 4614:         <table width="100%" border="0">
                   4615:           <tr bgcolor="#e6ffff">
1.174     albertel 4616:             <td colspan="2">
                   4617:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4618:             </td>
                   4619:           </tr>
                   4620:           <tr bgcolor="#ffffe6">
1.174     albertel 4621:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4622:           </tr>
                   4623:           <tr bgcolor="#ffffe6">
1.174     albertel 4624:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4625:           </tr>
1.82      albertel 4626:           <tr bgcolor="#ffffe6">
1.174     albertel 4627:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4628:           </tr>
1.157     albertel 4629:           <tr bgcolor="#ffffe6">
1.186     albertel 4630:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4631:           </tr>
                   4632:           <tr bgcolor="#ffffe6">
                   4633:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4634:           </tr>
                   4635:           <tr bgcolor="#ffffe6">
1.187     albertel 4636: 	    <td> Options: </td>
                   4637:             <td>
1.272     albertel 4638: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4639:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4640:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4641: 	    </td>
                   4642:           </tr>
                   4643:           <tr bgcolor="#ffffe6">
1.174     albertel 4644:             <td colspan="2">
1.265     www      4645:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4646:             </td>
                   4647:           </tr>
                   4648:         </table>
1.226     albertel 4649:        </td>
                   4650:      </form>
1.162     albertel 4651:     </tr>
                   4652: SCANTRONFORM
                   4653:    
                   4654:     $r->print($result);
                   4655: 
1.257     albertel 4656:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4657:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4658: 
1.422     foxr     4659: 	# Chunk of form to prompt for a scantron file upload.
                   4660: 
1.162     albertel 4661:         $r->print(<<SCANTRONFORM);
                   4662:     <tr>
                   4663:       <td bgcolor="#777777">
                   4664:         <table width="100%" border="0">
                   4665:           <tr bgcolor="#e6ffff">
                   4666:             <td>
1.174     albertel 4667:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4668:             </td>
                   4669:           </tr>
                   4670:           <tr bgcolor="#ffffe6">
                   4671:             <td>
                   4672: SCANTRONFORM
1.324     albertel 4673:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4674:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4675:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4676:     $r->print(<<UPLOAD);
                   4677:               <script type="text/javascript" language="javascript">
                   4678:     function checkUpload(formname) {
                   4679: 	if (formname.upfile.value == "") {
                   4680: 	    alert("Please use the browse button to select a file from your local directory.");
                   4681: 	    return false;
                   4682: 	}
                   4683: 	formname.submit();
                   4684:     }
                   4685:               </script>
                   4686: 
                   4687:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4688:                 $default_form_data
                   4689:                 <input name='courseid' type='hidden' value='$cnum' />
                   4690:                 <input name='domainid' type='hidden' value='$cdom' />
                   4691:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4692:                 File to upload:<input type="file" name="upfile" size="50" />
                   4693:                 <br />
                   4694:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4695:               </form>
                   4696: UPLOAD
1.162     albertel 4697: 
                   4698:         $r->print(<<SCANTRONFORM);
                   4699:             </td>
                   4700:           </tr>
1.75      albertel 4701:         </table>
                   4702:       </td>
                   4703:     </tr>
1.162     albertel 4704: SCANTRONFORM
                   4705:     }
1.422     foxr     4706: 
                   4707:     # Chunk of the form that prompts to view a scoring office file,
                   4708:     # corrected file, skipped records in a file.
                   4709: 
1.187     albertel 4710:     $r->print(<<SCANTRONFORM);
                   4711:     <tr>
1.226     albertel 4712:       <form action='/adm/grades' name='scantron_download'>
                   4713:         <td bgcolor="#777777">
1.379     albertel 4714: 	  $default_form_data
1.187     albertel 4715:           <input type="hidden" name="command" value="scantron_download" />
                   4716:           <table width="100%" border="0">
                   4717:             <tr bgcolor="#e6ffff">
                   4718:               <td colspan="2">
                   4719:                 &nbsp;<b>Download a scoring office file</b>
                   4720:               </td>
                   4721:             </tr>
                   4722:             <tr bgcolor="#ffffe6">
                   4723:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4724:             </tr>
                   4725:             <tr bgcolor="#ffffe6">
                   4726:               <td colspan="2">
1.293     www      4727:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4728:               </td>
                   4729:             </tr>
                   4730:           </table>
1.226     albertel 4731:         </td>
                   4732:       </form>
1.187     albertel 4733:     </tr>
                   4734: SCANTRONFORM
1.162     albertel 4735: 
                   4736:     $r->print(<<SCANTRONFORM);
1.75      albertel 4737:   </table>
1.81      albertel 4738: $grading_menu_button
1.75      albertel 4739: SCANTRONFORM
                   4740: 
1.162     albertel 4741:     return
1.75      albertel 4742: }
                   4743: 
1.423     albertel 4744: =pod
                   4745: 
                   4746: =item get_scantron_config
                   4747: 
                   4748:    Parse and return the scantron configuration line selected as a
                   4749:    hash of configuration file fields.
                   4750: 
                   4751:  Arguments:
                   4752:     which - the name of the configuration to parse from the file.
                   4753: 
                   4754: 
                   4755:  Returns:
                   4756:             If the named configuration is not in the file, an empty
                   4757:             hash is returned.
                   4758:     a hash with the fields
                   4759:       name         - internal name for the this configuration setup
                   4760:       description  - text to display to operator that describes this config
                   4761:       CODElocation - if 0 or the string 'none'
                   4762:                           - no CODE exists for this config
                   4763:                      if -1 || the string 'letter'
                   4764:                           - a CODE exists for this config and is
                   4765:                             a string of letters
                   4766:                      Unsupported value (but planned for future support)
                   4767:                           if a positive integer
                   4768:                                - The CODE exists as the first n items from
                   4769:                                  the question section of the form
                   4770:                           if the string 'number'
                   4771:                                - The CODE exists for this config and is
                   4772:                                  a string of numbers
                   4773:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4774:                      the CODE starts
                   4775:       CODElength  - length of the CODE
                   4776:       IDstart     - column where the student ID number starts
                   4777:       IDlength    - length of the student ID info
                   4778:       Qstart      - column where the information from the bubbled
                   4779:                     'questions' start
                   4780:       Qlength     - number of columns comprising a single bubble line from
                   4781:                     the sheet. (usually either 1 or 10)
1.424     albertel 4782:       Qon         - either a single character representing the character used
1.423     albertel 4783:                     to signal a bubble was chosen in the positional setup, or
                   4784:                     the string 'letter' if the letter of the chosen bubble is
                   4785:                     in the final, or 'number' if a number representing the
                   4786:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 4787:       Qoff        - the character used to represent that a bubble was
                   4788:                     left blank
1.423     albertel 4789:       PaperID     - if the scanning process generates a unique number for each
                   4790:                     sheet scanned the column that this ID number starts in
                   4791:       PaperIDlength - number of columns that comprise the unique ID number
                   4792:                       for the sheet of paper
1.424     albertel 4793:       FirstName   - column that the first name starts in
1.423     albertel 4794:       FirstNameLength - number of columns that the first name spans
                   4795:  
                   4796:       LastName    - column that the last name starts in
                   4797:       LastNameLength - number of columns that the last name spans
                   4798: 
                   4799: =cut
1.422     foxr     4800: 
1.82      albertel 4801: sub get_scantron_config {
                   4802:     my ($which) = @_;
                   4803:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4804:     my %config;
1.157     albertel 4805:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4806:     foreach my $line (<$fh>) {
                   4807: 	my ($name,$descrip)=split(/:/,$line);
                   4808: 	if ($name ne $which ) { next; }
                   4809: 	chomp($line);
                   4810: 	my @config=split(/:/,$line);
                   4811: 	$config{'name'}=$config[0];
                   4812: 	$config{'description'}=$config[1];
                   4813: 	$config{'CODElocation'}=$config[2];
                   4814: 	$config{'CODEstart'}=$config[3];
                   4815: 	$config{'CODElength'}=$config[4];
                   4816: 	$config{'IDstart'}=$config[5];
                   4817: 	$config{'IDlength'}=$config[6];
                   4818: 	$config{'Qstart'}=$config[7];
                   4819: 	$config{'Qlength'}=$config[8];
                   4820: 	$config{'Qoff'}=$config[9];
                   4821: 	$config{'Qon'}=$config[10];
1.157     albertel 4822: 	$config{'PaperID'}=$config[11];
                   4823: 	$config{'PaperIDlength'}=$config[12];
                   4824: 	$config{'FirstName'}=$config[13];
                   4825: 	$config{'FirstNamelength'}=$config[14];
                   4826: 	$config{'LastName'}=$config[15];
                   4827: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4828: 	last;
                   4829:     }
                   4830:     return %config;
                   4831: }
                   4832: 
1.423     albertel 4833: =pod 
                   4834: 
                   4835: =item username_to_idmap
                   4836: 
                   4837:     creates a hash keyed by student id with values of the corresponding
                   4838:     student username:domain.
                   4839: 
                   4840:   Arguments:
                   4841: 
                   4842:     $classlist - reference to the class list hash. This is a hash
                   4843:                  keyed by student name:domain  whose elements are references
1.424     albertel 4844:                  to arrays containing various chunks of information
1.423     albertel 4845:                  about the student. (See loncoursedata for more info).
                   4846: 
                   4847:   Returns
                   4848:     %idmap - the constructed hash
                   4849: 
                   4850: =cut
                   4851: 
1.82      albertel 4852: sub username_to_idmap {
                   4853:     my ($classlist)= @_;
                   4854:     my %idmap;
                   4855:     foreach my $student (keys(%$classlist)) {
                   4856: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4857: 	    $student;
                   4858:     }
                   4859:     return %idmap;
                   4860: }
1.423     albertel 4861: 
                   4862: =pod
                   4863: 
1.424     albertel 4864: =item scantron_fixup_scanline
1.423     albertel 4865: 
                   4866:    Process a requested correction to a scanline.
                   4867: 
                   4868:   Arguments:
                   4869:     $scantron_config   - hash from &get_scantron_config()
                   4870:     $scan_data         - hash of correction information 
                   4871:                           (see &scantron_getfile())
                   4872:     $line              - existing scanline
                   4873:     $whichline         - line number of the passed in scanline
                   4874:     $field             - type of change to process 
                   4875:                          (either 
                   4876:                           'ID'     -> correct the student ID number
                   4877:                           'CODE'   -> correct the CODE
                   4878:                           'answer' -> fixup the submitted answers)
                   4879:     
                   4880:    $args               - hash of additional info,
                   4881:                           - 'ID' 
                   4882:                                'newid' -> studentID to use in replacement
1.424     albertel 4883:                                           of existing one
1.423     albertel 4884:                           - 'CODE' 
                   4885:                                'CODE_ignore_dup' - set to true if duplicates
                   4886:                                                    should be ignored.
                   4887: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 4888:                                         if the existing unfound code should
1.423     albertel 4889:                                         be used as is
                   4890:                           - 'answer'
                   4891:                                'response' - new answer or 'none' if blank
                   4892:                                'question' - the bubble line to change
                   4893: 
                   4894:   Returns:
                   4895:     $line - the modified scanline
                   4896: 
                   4897:   Side effects: 
                   4898:     $scan_data - may be updated
                   4899: 
                   4900: =cut
                   4901: 
1.82      albertel 4902: 
1.157     albertel 4903: sub scantron_fixup_scanline {
                   4904:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.423     albertel 4905: 
1.157     albertel 4906:     if ($field eq 'ID') {
                   4907: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 4908: 	    return ($line,1,'New value too large');
1.157     albertel 4909: 	}
                   4910: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   4911: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   4912: 				     $args->{'newid'});
                   4913: 	}
                   4914: 	substr($line,$$scantron_config{'IDstart'}-1,
                   4915: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   4916: 	if ($args->{'newid'}=~/^\s*$/) {
                   4917: 	    &scan_data($scan_data,"$whichline.user",
                   4918: 		       $args->{'username'}.':'.$args->{'domain'});
                   4919: 	}
1.186     albertel 4920:     } elsif ($field eq 'CODE') {
1.192     albertel 4921: 	if ($args->{'CODE_ignore_dup'}) {
                   4922: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   4923: 	}
                   4924: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   4925: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 4926: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   4927: 		return ($line,1,'New CODE value too large');
                   4928: 	    }
                   4929: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   4930: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   4931: 	    }
                   4932: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   4933: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 4934: 	}
1.157     albertel 4935:     } elsif ($field eq 'answer') {
                   4936: 	my $length=$scantron_config->{'Qlength'};
                   4937: 	my $off=$scantron_config->{'Qoff'};
                   4938: 	my $on=$scantron_config->{'Qon'};
                   4939: 	my $answer=${off}x$length;
                   4940: 	if ($args->{'response'} eq 'none') {
                   4941: 	    &scan_data($scan_data,
                   4942: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   4943: 	} else {
1.274     albertel 4944: 	    if ($on eq 'letter') {
                   4945: 		my @alphabet=('A'..'Z');
                   4946: 		$answer=$alphabet[$args->{'response'}];
                   4947: 	    } elsif ($on eq 'number') {
                   4948: 		$answer=$args->{'response'}+1;
1.389     albertel 4949: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 4950: 	    } else {
                   4951: 		substr($answer,$args->{'response'},1)=$on;
                   4952: 	    }
1.157     albertel 4953: 	    &scan_data($scan_data,
                   4954: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   4955: 	}
                   4956: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   4957: 	substr($line,$where-1,$length)=$answer;
                   4958:     }
                   4959:     return $line;
                   4960: }
1.423     albertel 4961: 
                   4962: =pod
                   4963: 
                   4964: =item scan_data
                   4965: 
                   4966:     Edit or look up  an item in the scan_data hash.
                   4967: 
                   4968:   Arguments:
                   4969:     $scan_data  - The hash (see scantron_getfile)
                   4970:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 4971:                   scantronfilename_key).
1.423     albertel 4972:     $data        - New value of the hash entry.
                   4973:     $delete      - If true, the entry is removed from the hash.
                   4974: 
                   4975:   Returns:
                   4976:     The new value of the hash table field (undefined if deleted).
                   4977: 
                   4978: =cut
                   4979: 
                   4980: 
1.157     albertel 4981: sub scan_data {
                   4982:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 4983:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 4984:     if (defined($value)) {
                   4985: 	$scan_data->{$filename.'_'.$key} = $value;
                   4986:     }
                   4987:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   4988:     return $scan_data->{$filename.'_'.$key};
                   4989: }
1.423     albertel 4990: 
                   4991: =pod 
                   4992: 
                   4993: =item scantron_parse_scanline
                   4994: 
                   4995:   Decodes a scanline from the selected scantron file
                   4996: 
                   4997:  Arguments:
                   4998:     line             - The text of the scantron file line to process
                   4999:     whichline        - Line number
                   5000:     scantron_config  - Hash describing the format of the scantron lines.
                   5001:     scan_data        - Hash of extra information about the scanline
                   5002:                        (see scantron_getfile for more information)
                   5003:     just_header      - True if should not process question answers but only
                   5004:                        the stuff to the left of the answers.
                   5005:  Returns:
                   5006:    Hash containing the result of parsing the scanline
                   5007: 
                   5008:    Keys are all proceeded by the string 'scantron.'
                   5009: 
                   5010:        CODE    - the CODE in use for this scanline
                   5011:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5012:                  by the operator
                   5013:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5014:                             CODEs were selected, but the usage has been
                   5015:                             forced by the operator
                   5016:        ID  - student ID
                   5017:        PaperID - if used, the ID number printed on the sheet when the 
                   5018:                  paper was scanned
                   5019:        FirstName - first name from the sheet
                   5020:        LastName  - last name from the sheet
                   5021: 
                   5022:      if just_header was not true these key may also exist
                   5023: 
                   5024:        missingerror - a list of bubbled line numbers that had a blank bubble
                   5025:                       that is considered an error (if the operator had already
                   5026:                       okayed a blank bubble line as really being blank then
                   5027:                       that bubble line number won't appear here.
                   5028:        doubleerror  - a list of bubbled line numbers that had more than one
                   5029:                       bubble filled in and has not been corrected by the
                   5030:                       operator
                   5031:        maxquest     - the number of the last bubble line that was parsed
                   5032: 
                   5033:        (<number> starts at 1)
                   5034:        <number>.answer - zero or more letters representing the selected
                   5035:                          letters from the scanline for the bubble line 
                   5036:                          <number>.
                   5037:                          if blank there was either no bubble or there where
                   5038:                          multiple bubbles, (consult the keys missingerror and
                   5039:                          doubleerror if this is an error condition)
                   5040: 
                   5041: =cut
                   5042: 
1.82      albertel 5043: sub scantron_parse_scanline {
1.423     albertel 5044:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.82      albertel 5045:     my %record;
1.422     foxr     5046:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5047:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5048:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5049: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5050: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5051: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5052: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5053: 	    $record{'scantron.CODE'}=substr($data,
                   5054: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5055: 					    $$scantron_config{'CODElength'});
1.191     albertel 5056: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5057: 		$record{'scantron.useCODE'}=1;
                   5058: 	    }
1.192     albertel 5059: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5060: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5061: 	    }
1.82      albertel 5062: 	} else {
                   5063: 	    #FIXME interpret first N questions
                   5064: 	}
                   5065:     }
1.83      albertel 5066:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5067: 				  $$scantron_config{'IDlength'});
1.157     albertel 5068:     $record{'scantron.PaperID'}=
                   5069: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5070: 	       $$scantron_config{'PaperIDlength'});
                   5071:     $record{'scantron.FirstName'}=
                   5072: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5073: 	       $$scantron_config{'FirstNamelength'});
                   5074:     $record{'scantron.LastName'}=
                   5075: 	substr($data,$$scantron_config{'LastName'}-1,
                   5076: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5077:     if ($just_header) { return \%record; }
1.194     albertel 5078: 
1.82      albertel 5079:     my @alphabet=('A'..'Z');
                   5080:     my $questnum=0;
                   5081:     while ($questions) {
                   5082: 	$questnum++;
                   5083: 	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
                   5084: 	substr($questions,0,$$scantron_config{'Qlength'})='';
1.83      albertel 5085: 	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
1.239     albertel 5086: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.371     albertel 5087: 	    if ($currentquest eq '?'
                   5088: 		|| $currentquest eq '*') {
1.274     albertel 5089: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5090: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 5091: 	    } elsif (!defined($currentquest)
1.274     albertel 5092: 		     || $currentquest eq $$scantron_config{'Qoff'}
                   5093: 		     || $currentquest !~ /^[A-Z]$/) {
1.239     albertel 5094: 		$record{"scantron.$questnum.answer"}='';
                   5095: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5096: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5097: 		}
                   5098: 	    } else {
                   5099: 		$record{"scantron.$questnum.answer"}=$currentquest;
                   5100: 	    }
                   5101: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.371     albertel 5102: 	    if ($currentquest eq '?'
                   5103: 		|| $currentquest eq '*') {
1.274     albertel 5104: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5105: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 5106: 	    } elsif (!defined($currentquest)
                   5107: 		     || $currentquest eq $$scantron_config{'Qoff'} 
                   5108: 		     || $currentquest !~ /^\d$/) {
1.239     albertel 5109: 		$record{"scantron.$questnum.answer"}='';
                   5110: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5111: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5112: 		}
                   5113: 	    } else {
1.371     albertel 5114: 		# wrap zero back to J
                   5115: 		if ($currentquest eq '0') {
                   5116: 		    $record{"scantron.$questnum.answer"}=
                   5117: 			$alphabet[9];
                   5118: 		} else {
                   5119: 		    $record{"scantron.$questnum.answer"}=
                   5120: 			$alphabet[$currentquest-1];
                   5121: 		}
1.239     albertel 5122: 	    }
1.82      albertel 5123: 	} else {
1.239     albertel 5124: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
                   5125: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}) {
                   5126: 		$record{"scantron.$questnum.answer"}='';
                   5127: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5128: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5129: 		}
                   5130: 	    } else {
                   5131: 		$record{"scantron.$questnum.answer"}=
                   5132: 		    $alphabet[length($array[0])];
                   5133: 	    }
                   5134: 	    if (scalar(@array) gt 2) {
                   5135: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5136: 		my @ans=@array;
                   5137: 		my $i=length($ans[0]);shift(@ans);
                   5138: 		while ($#ans) {
                   5139: 		    $i+=length($ans[0])+1;
                   5140: 		    $record{"scantron.$questnum.answer"}.=$alphabet[$i];
                   5141: 		    shift(@ans);
                   5142: 		}
                   5143: 	    }
1.82      albertel 5144: 	}
                   5145:     }
1.83      albertel 5146:     $record{'scantron.maxquest'}=$questnum;
                   5147:     return \%record;
1.82      albertel 5148: }
                   5149: 
1.423     albertel 5150: =pod
                   5151: 
                   5152: =item scantron_add_delay
                   5153: 
                   5154:    Adds an error message that occurred during the grading phase to a
                   5155:    queue of messages to be shown after grading pass is complete
                   5156: 
                   5157:  Arguments:
1.424     albertel 5158:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5159:    $scanline    - the scanline that caused the error
                   5160:    $errormesage - the error message
                   5161:    $errorcode   - a numeric code for the error
                   5162: 
                   5163:  Side Effects:
1.424     albertel 5164:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5165: 
                   5166: =cut
                   5167: 
1.82      albertel 5168: sub scantron_add_delay {
1.140     albertel 5169:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5170:     push(@$delayqueue,
                   5171: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5172: 	  'ecode' => $errorcode }
                   5173: 	 );
1.82      albertel 5174: }
                   5175: 
1.423     albertel 5176: =pod
                   5177: 
                   5178: =item scantron_find_student
                   5179: 
1.424     albertel 5180:    Finds the username for the current scanline
                   5181: 
                   5182:   Arguments:
                   5183:    $scantron_record - hash result from scantron_parse_scanline
                   5184:    $scan_data       - hash of correction information 
                   5185:                       (see &scantron_getfile() form more information)
                   5186:    $idmap           - hash from &username_to_idmap()
                   5187:    $line            - number of current scanline
                   5188:  
                   5189:   Returns:
                   5190:    Either 'username:domain' or undef if unknown
                   5191: 
1.423     albertel 5192: =cut
                   5193: 
1.82      albertel 5194: sub scantron_find_student {
1.157     albertel 5195:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5196:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5197:     if ($scanID =~ /^\s*$/) {
                   5198:  	return &scan_data($scan_data,"$line.user");
                   5199:     }
1.83      albertel 5200:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5201:  	if (lc($id) eq lc($scanID)) {
                   5202:  	    return $$idmap{$id};
                   5203:  	}
1.83      albertel 5204:     }
                   5205:     return undef;
                   5206: }
                   5207: 
1.423     albertel 5208: =pod
                   5209: 
                   5210: =item scantron_filter
                   5211: 
1.424     albertel 5212:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5213:    hidden resources was selected
                   5214: 
1.423     albertel 5215: =cut
                   5216: 
1.83      albertel 5217: sub scantron_filter {
                   5218:     my ($curres)=@_;
1.331     albertel 5219: 
                   5220:     if (ref($curres) && $curres->is_problem()) {
                   5221: 	# if the user has asked to not have either hidden
                   5222: 	# or 'randomout' controlled resources to be graded
                   5223: 	# don't include them
                   5224: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5225: 	    && $curres->randomout) {
                   5226: 	    return 0;
                   5227: 	}
1.83      albertel 5228: 	return 1;
                   5229:     }
                   5230:     return 0;
1.82      albertel 5231: }
                   5232: 
1.423     albertel 5233: =pod
                   5234: 
                   5235: =item scantron_process_corrections
                   5236: 
1.424     albertel 5237:    Gets correction information out of submitted form data and corrects
                   5238:    the scanline
                   5239: 
1.423     albertel 5240: =cut
                   5241: 
1.157     albertel 5242: sub scantron_process_corrections {
                   5243:     my ($r) = @_;
1.257     albertel 5244:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5245:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5246:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5247:     my $which=$env{'form.scantron_line'};
1.200     albertel 5248:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5249:     my ($skip,$err,$errmsg);
1.257     albertel 5250:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5251: 	$skip=1;
1.257     albertel 5252:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5253: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5254: 	    $env{'form.scantron_domain'};
1.157     albertel 5255: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5256: 	($line,$err,$errmsg)=
                   5257: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5258: 				     'ID',{'newid'=>$newid,
1.257     albertel 5259: 				    'username'=>$env{'form.scantron_username'},
                   5260: 				    'domain'=>$env{'form.scantron_domain'}});
                   5261:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5262: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5263: 	my $newCODE;
1.192     albertel 5264: 	my %args;
1.190     albertel 5265: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5266: 	    $newCODE='use_unfound';
1.190     albertel 5267: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5268: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5269: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5270: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5271: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5272: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5273: 	}
1.257     albertel 5274: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5275: 	    $args{'CODE_ignore_dup'}=1;
                   5276: 	}
                   5277: 	$args{'CODE'}=$newCODE;
1.186     albertel 5278: 	($line,$err,$errmsg)=
                   5279: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5280: 				     'CODE',\%args);
1.257     albertel 5281:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5282: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5283: 	    ($line,$err,$errmsg)=
                   5284: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5285: 					 $which,'answer',
                   5286: 					 { 'question'=>$question,
1.257     albertel 5287: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5288: 	    if ($err) { last; }
                   5289: 	}
                   5290:     }
                   5291:     if ($err) {
1.398     albertel 5292: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5293:     } else {
1.200     albertel 5294: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5295: 	&scantron_putfile($scanlines,$scan_data);
                   5296:     }
                   5297: }
                   5298: 
1.423     albertel 5299: =pod
                   5300: 
                   5301: =item reset_skipping_status
                   5302: 
1.424     albertel 5303:    Forgets the current set of remember skipped scanlines (and thus
                   5304:    reverts back to considering all lines in the
                   5305:    scantron_skipped_<filename> file)
                   5306: 
1.423     albertel 5307: =cut
                   5308: 
1.200     albertel 5309: sub reset_skipping_status {
                   5310:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5311:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5312:     &scantron_putfile(undef,$scan_data);
                   5313: }
                   5314: 
1.423     albertel 5315: =pod
                   5316: 
                   5317: =item start_skipping
                   5318: 
1.424     albertel 5319:    Marks a scanline to be skipped. 
                   5320: 
1.423     albertel 5321: =cut
                   5322: 
1.376     albertel 5323: sub start_skipping {
1.200     albertel 5324:     my ($scan_data,$i)=@_;
                   5325:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5326:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5327: 	$remembered{$i}=2;
                   5328:     } else {
                   5329: 	$remembered{$i}=1;
                   5330:     }
1.200     albertel 5331:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5332: }
                   5333: 
1.423     albertel 5334: =pod
                   5335: 
                   5336: =item should_be_skipped
                   5337: 
1.424     albertel 5338:    Checks whether a scanline should be skipped.
                   5339: 
1.423     albertel 5340: =cut
                   5341: 
1.200     albertel 5342: sub should_be_skipped {
1.376     albertel 5343:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5344:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5345: 	# not redoing old skips
1.376     albertel 5346: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5347: 	return 0;
                   5348:     }
                   5349:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5350: 
                   5351:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5352: 	return 0;
                   5353:     }
1.200     albertel 5354:     return 1;
                   5355: }
                   5356: 
1.423     albertel 5357: =pod
                   5358: 
                   5359: =item remember_current_skipped
                   5360: 
1.424     albertel 5361:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5362:    file and remembers them into scan_data for later use.
                   5363: 
1.423     albertel 5364: =cut
                   5365: 
1.200     albertel 5366: sub remember_current_skipped {
                   5367:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5368:     my %to_remember;
                   5369:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5370: 	if ($scanlines->{'skipped'}[$i]) {
                   5371: 	    $to_remember{$i}=1;
                   5372: 	}
                   5373:     }
1.376     albertel 5374: 
1.200     albertel 5375:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5376:     &scantron_putfile(undef,$scan_data);
                   5377: }
                   5378: 
1.423     albertel 5379: =pod
                   5380: 
                   5381: =item check_for_error
                   5382: 
1.424     albertel 5383:     Checks if there was an error when attempting to remove a specific
                   5384:     scantron_.. bubble sheet data file. Prints out an error if
                   5385:     something went wrong.
                   5386: 
1.423     albertel 5387: =cut
                   5388: 
1.200     albertel 5389: sub check_for_error {
                   5390:     my ($r,$result)=@_;
                   5391:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5392: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5393:     }
                   5394: }
1.157     albertel 5395: 
1.423     albertel 5396: =pod
                   5397: 
                   5398: =item scantron_warning_screen
                   5399: 
1.424     albertel 5400:    Interstitial screen to make sure the operator has selected the
                   5401:    correct options before we start the validation phase.
                   5402: 
1.423     albertel 5403: =cut
                   5404: 
1.203     albertel 5405: sub scantron_warning_screen {
                   5406:     my ($button_text)=@_;
1.257     albertel 5407:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5408:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5409:     my $CODElist;
1.284     albertel 5410:     if ($scantron_config{'CODElocation'} &&
                   5411: 	$scantron_config{'CODEstart'} &&
                   5412: 	$scantron_config{'CODElength'}) {
                   5413: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5414: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5415: 	$CODElist=
                   5416: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5417: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5418:     }
1.203     albertel 5419:     return (<<STUFF);
                   5420: <p>
1.398     albertel 5421: <span class="LC_warning">Please double check the information
                   5422:                  below before clicking on '$button_text'</span>
1.203     albertel 5423: </p>
                   5424: <table>
1.284     albertel 5425: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5426: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5427: $CODElist
1.203     albertel 5428: </table>
                   5429: <br />
                   5430: <p> If this information is correct, please click on '$button_text'.</p>
                   5431: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5432: 
                   5433: <br />
                   5434: STUFF
                   5435: }
                   5436: 
1.423     albertel 5437: =pod
                   5438: 
                   5439: =item scantron_do_warning
                   5440: 
1.424     albertel 5441:    Check if the operator has picked something for all required
                   5442:    fields. Error out if something is missing.
                   5443: 
1.423     albertel 5444: =cut
                   5445: 
1.203     albertel 5446: sub scantron_do_warning {
                   5447:     my ($r)=@_;
1.324     albertel 5448:     my ($symb)=&get_symb($r);
1.203     albertel 5449:     if (!$symb) {return '';}
1.324     albertel 5450:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5451:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5452:     if ( $env{'form.selectpage'} eq '' ||
                   5453: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5454: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5455: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5456: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5457: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5458: 	} 
1.257     albertel 5459: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5460: 	    $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 5461: 	} 
1.257     albertel 5462: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5463: 	    $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 5464: 	} 
                   5465:     } else {
1.265     www      5466: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5467: 	$r->print(<<STUFF);
1.203     albertel 5468: $warning
1.265     www      5469: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5470: <input type="hidden" name="command" value="scantron_validate" />
                   5471: STUFF
1.237     albertel 5472:     }
1.352     albertel 5473:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5474:     return '';
                   5475: }
                   5476: 
1.423     albertel 5477: =pod
                   5478: 
                   5479: =item scantron_form_start
                   5480: 
1.424     albertel 5481:     html hidden input for remembering all selected grading options
                   5482: 
1.423     albertel 5483: =cut
                   5484: 
1.203     albertel 5485: sub scantron_form_start {
                   5486:     my ($max_bubble)=@_;
                   5487:     my $result= <<SCANTRONFORM;
                   5488: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5489:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5490:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5491:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5492:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5493:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5494:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5495:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5496:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5497:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5498: SCANTRONFORM
                   5499:     return $result;
                   5500: }
                   5501: 
1.423     albertel 5502: =pod
                   5503: 
                   5504: =item scantron_validate_file
                   5505: 
1.424     albertel 5506:     Dispatch routine for doing validation of a bubble sheet data file.
                   5507: 
                   5508:     Also processes any necessary information resets that need to
                   5509:     occur before validation begins (ignore previous corrections,
                   5510:     restarting the skipped records processing)
                   5511: 
1.423     albertel 5512: =cut
                   5513: 
1.157     albertel 5514: sub scantron_validate_file {
                   5515:     my ($r) = @_;
1.324     albertel 5516:     my ($symb)=&get_symb($r);
1.157     albertel 5517:     if (!$symb) {return '';}
1.324     albertel 5518:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5519:     
                   5520:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5521:     # them when doing the corrections reset
1.257     albertel 5522:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5523: 	&reset_skipping_status();
                   5524:     }
1.257     albertel 5525:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5526: 	&remember_current_skipped();
1.257     albertel 5527: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5528:     }
                   5529: 
1.257     albertel 5530:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5531: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5532: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5533: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5534: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5535:     }
1.200     albertel 5536: 
1.257     albertel 5537:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5538: 	&scantron_process_corrections($r);
                   5539:     }
1.424     albertel 5540:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5541:     #get the student pick code ready
                   5542:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5543:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5544:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5545:     $r->print($result);
                   5546:     
1.334     albertel 5547:     my @validate_phases=( 'sequence',
                   5548: 			  'ID',
1.157     albertel 5549: 			  'CODE',
                   5550: 			  'doublebubble',
                   5551: 			  'missingbubbles');
1.257     albertel 5552:     if (!$env{'form.validatepass'}) {
                   5553: 	$env{'form.validatepass'} = 0;
1.157     albertel 5554:     }
1.257     albertel 5555:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5556: 
                   5557:     my $stop=0;
                   5558:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5559: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5560: 	$r->rflush();
                   5561: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5562: 	{
                   5563: 	    no strict 'refs';
                   5564: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5565: 	}
                   5566:     }
                   5567:     if (!$stop) {
1.203     albertel 5568: 	my $warning=&scantron_warning_screen('Start Grading');
                   5569: 	$r->print(<<STUFF);
                   5570: Validation process complete.<br />
                   5571: $warning
                   5572: <input type="submit" name="submit" value="Start Grading" />
                   5573: <input type="hidden" name="command" value="scantron_process" />
                   5574: STUFF
                   5575: 
1.157     albertel 5576:     } else {
                   5577: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5578: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5579:     }
                   5580:     if ($stop) {
1.334     albertel 5581: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5582: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5583: 	    $r->print(' this error <br />');
                   5584: 
                   5585: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5586: 	} else {
                   5587: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5588: 	    $r->print(' using corrected info <br />');
                   5589: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5590: 	    $r->print(" this scanline saving it for later.");
                   5591: 	}
1.157     albertel 5592:     }
1.352     albertel 5593:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5594:     return '';
                   5595: }
                   5596: 
1.423     albertel 5597: 
                   5598: =pod
                   5599: 
                   5600: =item scantron_remove_file
                   5601: 
1.424     albertel 5602:    Removes the requested bubble sheet data file, makes sure that
                   5603:    scantron_original_<filename> is never removed
                   5604: 
                   5605: 
1.423     albertel 5606: =cut
                   5607: 
1.200     albertel 5608: sub scantron_remove_file {
1.192     albertel 5609:     my ($which)=@_;
1.257     albertel 5610:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5611:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5612:     my $file='scantron_';
1.200     albertel 5613:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5614: 	$file.=$which.'_';
1.192     albertel 5615:     } else {
                   5616: 	return 'refused';
                   5617:     }
1.257     albertel 5618:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5619:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5620: }
                   5621: 
1.423     albertel 5622: 
                   5623: =pod
                   5624: 
                   5625: =item scantron_remove_scan_data
                   5626: 
1.424     albertel 5627:    Removes all scan_data correction for the requested bubble sheet
                   5628:    data file.  (In the case that both the are doing skipped records we need
                   5629:    to remember the old skipped lines for the time being so that element
                   5630:    persists for a while.)
                   5631: 
1.423     albertel 5632: =cut
                   5633: 
1.200     albertel 5634: sub scantron_remove_scan_data {
1.257     albertel 5635:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5636:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5637:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5638:     my @todelete;
1.257     albertel 5639:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5640:     foreach my $key (@keys) {
                   5641: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5642: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5643: 		$key=~/remember_skipping/) {
                   5644: 		next;
                   5645: 	    }
1.192     albertel 5646: 	    push(@todelete,$key);
                   5647: 	}
                   5648:     }
1.200     albertel 5649:     my $result;
1.192     albertel 5650:     if (@todelete) {
1.200     albertel 5651: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5652:     }
                   5653:     return $result;
                   5654: }
                   5655: 
1.423     albertel 5656: 
                   5657: =pod
                   5658: 
                   5659: =item scantron_getfile
                   5660: 
1.424     albertel 5661:     Fetches the requested bubble sheet data file (all 3 versions), and
                   5662:     the scan_data hash
                   5663:   
                   5664:   Arguments:
                   5665:     None
                   5666: 
                   5667:   Returns:
                   5668:     2 hash references
                   5669: 
                   5670:      - first one has 
                   5671:          orig      -
                   5672:          corrected -
                   5673:          skipped   -  each of which points to an array ref of the specified
                   5674:                       file broken up into individual lines
                   5675:          count     - number of scanlines
                   5676:  
                   5677:      - second is the scan_data hash possible keys are
1.425     albertel 5678:        ($number refers to scanline numbered $number and thus the key affects
                   5679:         only that scanline
                   5680:         $bubline refers to the specific bubble line element and the aspects
                   5681:         refers to that specific bubble line element)
                   5682: 
                   5683:        $number.user - username:domain to use
                   5684:        $number.CODE_ignore_dup 
                   5685:                     - ignore the duplicate CODE error 
                   5686:        $number.useCODE
                   5687:                     - use the CODE in the scanline as is
                   5688:        $number.no_bubble.$bubline
                   5689:                     - it is valid that there is no bubbled in bubble
                   5690:                       at $number $bubline
                   5691:        remember_skipping
                   5692:                     - a frozen hash containing keys of $number and values
                   5693:                       of either 
                   5694:                         1 - we are on a 'do skipped records pass' and plan
                   5695:                             on processing this line
                   5696:                         2 - we are on a 'do skipped records pass' and this
                   5697:                             scanline has been marked to skip yet again
1.424     albertel 5698: 
1.423     albertel 5699: =cut
                   5700: 
1.157     albertel 5701: sub scantron_getfile {
1.200     albertel 5702:     #FIXME really would prefer a scantron directory
1.257     albertel 5703:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5704:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5705:     my $lines;
                   5706:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5707: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5708:     my %scanlines;
                   5709:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5710:     my $temp=$scanlines{'orig'};
                   5711:     $scanlines{'count'}=$#$temp;
                   5712: 
                   5713:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5714: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5715:     if ($lines eq '-1') {
                   5716: 	$scanlines{'corrected'}=[];
                   5717:     } else {
                   5718: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5719:     }
                   5720:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5721: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5722:     if ($lines eq '-1') {
                   5723: 	$scanlines{'skipped'}=[];
                   5724:     } else {
                   5725: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5726:     }
1.175     albertel 5727:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5728:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5729:     my %scan_data = @tmp;
                   5730:     return (\%scanlines,\%scan_data);
                   5731: }
                   5732: 
1.423     albertel 5733: =pod
                   5734: 
                   5735: =item lonnet_putfile
                   5736: 
1.424     albertel 5737:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   5738: 
                   5739:  Arguments:
                   5740:    $contents - data to store
                   5741:    $filename - filename to store $contents into
                   5742: 
                   5743:  Returns:
                   5744:    result value from &Apache::lonnet::finishuserfileupload
                   5745: 
1.423     albertel 5746: =cut
                   5747: 
1.157     albertel 5748: sub lonnet_putfile {
                   5749:     my ($contents,$filename)=@_;
1.257     albertel 5750:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5751:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5752:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 5753:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 5754: 
                   5755: }
                   5756: 
1.423     albertel 5757: =pod
                   5758: 
                   5759: =item scantron_putfile
                   5760: 
1.424     albertel 5761:     Stores the current version of the bubble sheet data files, and the
                   5762:     scan_data hash. (Does not modify the original version only the
                   5763:     corrected and skipped versions.
                   5764: 
                   5765:  Arguments:
                   5766:     $scanlines - hash ref that looks like the first return value from
                   5767:                  &scantron_getfile()
                   5768:     $scan_data - hash ref that looks like the second return value from
                   5769:                  &scantron_getfile()
                   5770: 
1.423     albertel 5771: =cut
                   5772: 
1.157     albertel 5773: sub scantron_putfile {
                   5774:     my ($scanlines,$scan_data) = @_;
1.200     albertel 5775:     #FIXME really would prefer a scantron directory
1.257     albertel 5776:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5777:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 5778:     if ($scanlines) {
                   5779: 	my $prefix='scantron_';
1.157     albertel 5780: # no need to update orig, shouldn't change
                   5781: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 5782: #		    $env{'form.scantron_selectfile'});
1.200     albertel 5783: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   5784: 			$prefix.'corrected_'.
1.257     albertel 5785: 			$env{'form.scantron_selectfile'});
1.200     albertel 5786: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   5787: 			$prefix.'skipped_'.
1.257     albertel 5788: 			$env{'form.scantron_selectfile'});
1.200     albertel 5789:     }
1.175     albertel 5790:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 5791: }
                   5792: 
1.423     albertel 5793: =pod
                   5794: 
                   5795: =item scantron_get_line
                   5796: 
1.424     albertel 5797:    Returns the correct version of the scanline
                   5798: 
                   5799:  Arguments:
                   5800:     $scanlines - hash ref that looks like the first return value from
                   5801:                  &scantron_getfile()
                   5802:     $scan_data - hash ref that looks like the second return value from
                   5803:                  &scantron_getfile()
                   5804:     $i         - number of the requested line (starts at 0)
                   5805: 
                   5806:  Returns:
                   5807:    A scanline, (either the original or the corrected one if it
                   5808:    exists), or undef if the requested scanline should be
                   5809:    skipped. (Either because it's an skipped scanline, or it's an
                   5810:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   5811:    pass.
                   5812: 
1.423     albertel 5813: =cut
                   5814: 
1.157     albertel 5815: sub scantron_get_line {
1.200     albertel 5816:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 5817:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   5818:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 5819:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   5820:     return $scanlines->{'orig'}[$i]; 
                   5821: }
                   5822: 
1.423     albertel 5823: =pod
                   5824: 
                   5825: =item scantron_todo_count
                   5826: 
1.424     albertel 5827:     Counts the number of scanlines that need processing.
                   5828: 
                   5829:  Arguments:
                   5830:     $scanlines - hash ref that looks like the first return value from
                   5831:                  &scantron_getfile()
                   5832:     $scan_data - hash ref that looks like the second return value from
                   5833:                  &scantron_getfile()
                   5834: 
                   5835:  Returns:
                   5836:     $count - number of scanlines to process
                   5837: 
1.423     albertel 5838: =cut
                   5839: 
1.200     albertel 5840: sub get_todo_count {
                   5841:     my ($scanlines,$scan_data)=@_;
                   5842:     my $count=0;
                   5843:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5844: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   5845: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5846: 	$count++;
                   5847:     }
                   5848:     return $count;
                   5849: }
                   5850: 
1.423     albertel 5851: =pod
                   5852: 
                   5853: =item scantron_put_line
                   5854: 
1.424     albertel 5855:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   5856:     data file.
                   5857: 
                   5858:  Arguments:
                   5859:     $scanlines - hash ref that looks like the first return value from
                   5860:                  &scantron_getfile()
                   5861:     $scan_data - hash ref that looks like the second return value from
                   5862:                  &scantron_getfile()
                   5863:     $i         - line number to update
                   5864:     $newline   - contents of the updated scanline
                   5865:     $skip      - if true make the line for skipping and update the
                   5866:                  'skipped' file
                   5867: 
1.423     albertel 5868: =cut
                   5869: 
1.157     albertel 5870: sub scantron_put_line {
1.200     albertel 5871:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 5872:     if ($skip) {
                   5873: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 5874: 	&start_skipping($scan_data,$i);
1.157     albertel 5875: 	return;
                   5876:     }
                   5877:     $scanlines->{'corrected'}[$i]=$newline;
                   5878: }
                   5879: 
1.423     albertel 5880: =pod
                   5881: 
                   5882: =item scantron_clear_skip
                   5883: 
1.424     albertel 5884:    Remove a line from the 'skipped' file
                   5885: 
                   5886:  Arguments:
                   5887:     $scanlines - hash ref that looks like the first return value from
                   5888:                  &scantron_getfile()
                   5889:     $scan_data - hash ref that looks like the second return value from
                   5890:                  &scantron_getfile()
                   5891:     $i         - line number to update
                   5892: 
1.423     albertel 5893: =cut
                   5894: 
1.376     albertel 5895: sub scantron_clear_skip {
                   5896:     my ($scanlines,$scan_data,$i)=@_;
                   5897:     if (exists($scanlines->{'skipped'}[$i])) {
                   5898: 	undef($scanlines->{'skipped'}[$i]);
                   5899: 	return 1;
                   5900:     }
                   5901:     return 0;
                   5902: }
                   5903: 
1.423     albertel 5904: =pod
                   5905: 
                   5906: =item scantron_filter_not_exam
                   5907: 
1.424     albertel 5908:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   5909:    filter out resources that are not marked as 'exam' mode
                   5910: 
1.423     albertel 5911: =cut
                   5912: 
1.334     albertel 5913: sub scantron_filter_not_exam {
                   5914:     my ($curres)=@_;
                   5915:     
                   5916:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   5917: 	# if the user has asked to not have either hidden
                   5918: 	# or 'randomout' controlled resources to be graded
                   5919: 	# don't include them
                   5920: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5921: 	    && $curres->randomout) {
                   5922: 	    return 0;
                   5923: 	}
                   5924: 	return 1;
                   5925:     }
                   5926:     return 0;
                   5927: }
                   5928: 
1.423     albertel 5929: =pod
                   5930: 
                   5931: =item scantron_validate_sequence
                   5932: 
1.424     albertel 5933:     Validates the selected sequence, checking for resource that are
                   5934:     not set to exam mode.
                   5935: 
1.423     albertel 5936: =cut
                   5937: 
1.334     albertel 5938: sub scantron_validate_sequence {
                   5939:     my ($r,$currentphase) = @_;
                   5940: 
                   5941:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5942:     my (undef,undef,$sequence)=
                   5943: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   5944: 
                   5945:     my $map=$navmap->getResourceByUrl($sequence);
                   5946: 
                   5947:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   5948:                                     value="ignore" />');
                   5949:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   5950: 	my @resources=
                   5951: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   5952: 	if (@resources) {
1.357     banghart 5953: 	    $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 5954: 	    return (1,$currentphase);
                   5955: 	}
                   5956:     }
                   5957: 
                   5958:     return (0,$currentphase+1);
                   5959: }
                   5960: 
1.423     albertel 5961: =pod
                   5962: 
                   5963: =item scantron_validate_ID
                   5964: 
1.424     albertel 5965:    Validates all scanlines in the selected file to not have any
                   5966:    invalid or underspecified student IDs
                   5967: 
1.423     albertel 5968: =cut
                   5969: 
1.157     albertel 5970: sub scantron_validate_ID {
                   5971:     my ($r,$currentphase) = @_;
                   5972:     
                   5973:     #get student info
                   5974:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5975:     my %idmap=&username_to_idmap($classlist);
                   5976: 
                   5977:     #get scantron line setup
1.257     albertel 5978:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5979:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5980: 
                   5981:     my %found=('ids'=>{},'usernames'=>{});
                   5982:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5983: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5984: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5985: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5986: 						 $scan_data);
                   5987: 	my $id=$$scan_record{'scantron.ID'};
                   5988: 	my $found;
                   5989: 	foreach my $checkid (keys(%idmap)) {
                   5990: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   5991: 	}
                   5992: 	if ($found) {
                   5993: 	    my $username=$idmap{$found};
                   5994: 	    if ($found{'ids'}{$found}) {
                   5995: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5996: 					 $line,'duplicateID',$found);
1.194     albertel 5997: 		return(1,$currentphase);
1.157     albertel 5998: 	    } elsif ($found{'usernames'}{$username}) {
                   5999: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6000: 					 $line,'duplicateID',$username);
1.194     albertel 6001: 		return(1,$currentphase);
1.157     albertel 6002: 	    }
1.186     albertel 6003: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6004: 	    $found{'ids'}{$found}++;
                   6005: 	    $found{'usernames'}{$username}++;
                   6006: 	} else {
                   6007: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6008: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6009: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6010: 		    &scantron_get_correction($r,$i,$scan_record,
                   6011: 					     \%scantron_config,
                   6012: 					     $line,'duplicateID',$username);
1.194     albertel 6013: 		    return(1,$currentphase);
1.157     albertel 6014: 		} elsif (!defined($username)) {
                   6015: 		    &scantron_get_correction($r,$i,$scan_record,
                   6016: 					     \%scantron_config,
                   6017: 					     $line,'incorrectID');
1.194     albertel 6018: 		    return(1,$currentphase);
1.157     albertel 6019: 		}
                   6020: 		$found{'usernames'}{$username}++;
                   6021: 	    } else {
                   6022: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6023: 					 $line,'incorrectID');
1.194     albertel 6024: 		return(1,$currentphase);
1.157     albertel 6025: 	    }
                   6026: 	}
                   6027:     }
                   6028: 
                   6029:     return (0,$currentphase+1);
                   6030: }
                   6031: 
1.423     albertel 6032: =pod
                   6033: 
                   6034: =item scantron_get_correction
                   6035: 
1.424     albertel 6036:    Builds the interface screen to interact with the operator to fix a
                   6037:    specific error condition in a specific scanline
                   6038: 
                   6039:  Arguments:
                   6040:     $r           - Apache request object
                   6041:     $i           - number of the current scanline
                   6042:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6043:     $scan_config - hash ref as returned from &get_scantron_config()
                   6044:     $line        - full contents of the current scanline
                   6045:     $error       - error condition, valid values are
                   6046:                    'incorrectCODE', 'duplicateCODE',
                   6047:                    'doublebubble', 'missingbubble',
                   6048:                    'duplicateID', 'incorrectID'
                   6049:     $arg         - extra information needed
                   6050:        For errors:
                   6051:          - duplicateID   - paper number that this studentID was seen before on
                   6052:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6053:                            seen on before
                   6054:          - incorrectCODE - current incorrect CODE 
                   6055:          - doublebubble  - array ref of the bubble lines that have double
                   6056:                            bubble errors
                   6057:          - missingbubble - array ref of the bubble lines that have missing
                   6058:                            bubble errors
                   6059: 
1.423     albertel 6060: =cut
                   6061: 
1.157     albertel 6062: sub scantron_get_correction {
                   6063:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6064: 
                   6065: #FIXME in the case of a duplicated ID the previous line, probaly need
                   6066: #to show both the current line and the previous one and allow skipping
                   6067: #the previous one or the current one
                   6068: 
1.161     albertel 6069:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6070:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6071: 	$r->print(" for PaperID <tt>".
                   6072: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6073:     } else {
                   6074: 	$r->print(" in scanline $i <pre>".
                   6075: 		  $line."</pre> \n");
                   6076:     }
1.242     albertel 6077:     my $message="<p>The ID on the form is  <tt>".
                   6078: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6079: 	"The name on the paper is ".
                   6080: 	$$scan_record{'scantron.LastName'}.",".
                   6081: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6082: 
1.157     albertel 6083:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6084:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6085:     if ($error =~ /ID$/) {
1.186     albertel 6086: 	if ($error eq 'incorrectID') {
1.157     albertel 6087: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6088: 	} elsif ($error eq 'duplicateID') {
                   6089: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6090: 	}
1.242     albertel 6091: 	$r->print($message);
1.157     albertel 6092: 	$r->print("<p>How should I handle this? <br /> \n");
                   6093: 	$r->print("\n<ul><li> ");
                   6094: 	#FIXME it would be nice if this sent back the user ID and
                   6095: 	#could do partial userID matches
                   6096: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6097: 				       'scantron_username','scantron_domain'));
                   6098: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6099: 	$r->print("\n@".
1.257     albertel 6100: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6101: 
                   6102: 	$r->print('</li>');
1.186     albertel 6103:     } elsif ($error =~ /CODE$/) {
                   6104: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6105: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6106: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6107: 	    $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 6108: 	}
1.224     albertel 6109: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6110: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6111: 	$r->print($message);
1.186     albertel 6112: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6113: 	$r->print("\n<br /> ");
1.194     albertel 6114: 	my $i=0;
1.273     albertel 6115: 	if ($error eq 'incorrectCODE' 
                   6116: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6117: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6118: 	    if ($closest > 0) {
                   6119: 		foreach my $testcode (@{$closest}) {
                   6120: 		    my $checked='';
1.401     albertel 6121: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6122: 		    $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' />");
                   6123: 		    $r->print("\n<br />");
                   6124: 		    $i++;
                   6125: 		}
1.194     albertel 6126: 	    }
                   6127: 	}
1.273     albertel 6128: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6129: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6130: 	    $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>");
                   6131: 	    $r->print("\n<br />");
                   6132: 	}
1.194     albertel 6133: 
1.188     albertel 6134: 	$r->print(<<ENDSCRIPT);
                   6135: <script type="text/javascript">
                   6136: function change_radio(field) {
1.190     albertel 6137:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6138:     var i;
                   6139:     for (i=0;i<slct.length;i++) {
                   6140:         if (slct[i].value==field) { slct[i].checked=true; }
                   6141:     }
                   6142: }
                   6143: </script>
                   6144: ENDSCRIPT
1.187     albertel 6145: 	my $href="/adm/pickcode?".
1.359     www      6146: 	   "form=".&escape("scantronupload").
                   6147: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6148: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6149: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6150: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6151: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6152: 	    $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')\" />");
                   6153: 	    $r->print("\n<br />");
                   6154: 	}
1.272     albertel 6155: 	$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 6156: 	$r->print("\n<br /><br />");
1.157     albertel 6157:     } elsif ($error eq 'doublebubble') {
                   6158: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6159: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6160: 		  join(',',@{$arg}).'" />');
1.242     albertel 6161: 	$r->print($message);
1.157     albertel 6162: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6163: 	foreach my $question (@{$arg}) {
                   6164: 	    my $selected=$$scan_record{"scantron.$question.answer"};
1.422     foxr     6165: 	    &scantron_bubble_selector($r,$scan_config,$question,
                   6166: 				      split('',$selected));
1.157     albertel 6167: 	}
                   6168:     } elsif ($error eq 'missingbubble') {
                   6169: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6170: 	$r->print($message);
1.157     albertel 6171: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6172: 	$r->print("Some questions have no scanned bubbles\n");
                   6173: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6174: 		  join(',',@{$arg}).'" />');
                   6175: 	foreach my $question (@{$arg}) {
                   6176: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   6177: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   6178: 	}
                   6179:     } else {
                   6180: 	$r->print("\n<ul>");
                   6181:     }
                   6182:     $r->print("\n</li></ul>");
                   6183: 
                   6184: }
1.423     albertel 6185: 
                   6186: =pod
                   6187: 
                   6188: =item scantron_bubble_selector
                   6189:   
                   6190:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6191:    possibly showing the existing the selected bubbles if known
1.423     albertel 6192: 
                   6193:  Arguments:
                   6194:     $r           - Apache request object
                   6195:     $scan_config - hash from &get_scantron_config()
                   6196:     $quest       - number of the bubble line to make a corrector for
                   6197:     $selected    - array of letters of previously selected bubbles
                   6198:     $lines       - if present, number of bubble lines to show
                   6199: 
                   6200: =cut
                   6201: 
1.157     albertel 6202: sub scantron_bubble_selector {
1.422     foxr     6203:     my ($r,$scan_config,$quest,@selected, $lines)=@_;
1.157     albertel 6204:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6205: 
                   6206:     my $scmode=$$scan_config{'Qon'};
                   6207:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6208: 
1.422     foxr     6209: 
                   6210:     if (!defined($lines)) {
                   6211: 	$lines = 1;
                   6212:     }
                   6213:     my $total_lines = $lines*2;
1.157     albertel 6214:     my @alphabet=('A'..'Z');
1.422     foxr     6215:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6216: 
                   6217:     for (my $l = 0; $l < $lines; $l++) {
                   6218: 	if ($l != 0) {
                   6219: 	    $r->print('<tr>');
                   6220: 	}
                   6221: 
                   6222: 	# FIXME:  This loop probably has to be considerably more clever for
                   6223: 	#  multiline bubbles: User can multibubble by having bubbles in
                   6224: 	#  several lines.  User can skip lines legitimately etc. etc.
                   6225: 
                   6226: 	for (my $i=0;$i<$max;$i++) {
                   6227: 	    $r->print("\n".'<td align="center">');
                   6228: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6229: 		$r->print('X'); 
                   6230: 		shift(@selected) ;
                   6231: 	    } else { 
                   6232: 		$r->print('&nbsp;'); 
                   6233: 	    }
                   6234: 	    $r->print('</td>');
                   6235: 	    
                   6236: 	}
                   6237: 
                   6238: 	if ($l == 0) {
                   6239: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6240: 
                   6241: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6242: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6243: 	
                   6244: 	}
                   6245: 
                   6246: 	$r->print('</tr><tr>');
                   6247: 
                   6248: 	# FIXME: This may have to be a bit more clever for
                   6249: 	#        multiline questions (different values e.g..).
                   6250: 
                   6251: 	for (my $i=0;$i<$max;$i++) {
                   6252: 	    $r->print("\n".
                   6253: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6254: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6255: 	}
                   6256: 	$r->print('</tr>');
                   6257: 
                   6258: 	    
1.157     albertel 6259:     }
1.422     foxr     6260:     $r->print('</table>');
1.157     albertel 6261: }
                   6262: 
1.423     albertel 6263: =pod
                   6264: 
                   6265: =item num_matches
                   6266: 
1.424     albertel 6267:    Counts the number of characters that are the same between the two arguments.
                   6268: 
                   6269:  Arguments:
                   6270:    $orig - CODE from the scanline
                   6271:    $code - CODE to match against
                   6272: 
                   6273:  Returns:
                   6274:    $count - integer count of the number of same characters between the
                   6275:             two arguments
                   6276: 
1.423     albertel 6277: =cut
                   6278: 
1.194     albertel 6279: sub num_matches {
                   6280:     my ($orig,$code) = @_;
                   6281:     my @code=split(//,$code);
                   6282:     my @orig=split(//,$orig);
                   6283:     my $same=0;
                   6284:     for (my $i=0;$i<scalar(@code);$i++) {
                   6285: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6286:     }
                   6287:     return $same;
                   6288: }
                   6289: 
1.423     albertel 6290: =pod
                   6291: 
                   6292: =item scantron_get_closely_matching_CODEs
                   6293: 
1.424     albertel 6294:    Cycles through all CODEs and finds the set that has the greatest
                   6295:    number of same characters as the provided CODE
                   6296: 
                   6297:  Arguments:
                   6298:    $allcodes - hash ref returned by &get_codes()
                   6299:    $CODE     - CODE from the current scanline
                   6300: 
                   6301:  Returns:
                   6302:    2 element list
                   6303:     - first elements is number of how closely matching the best fit is 
                   6304:       (5 means best set has 5 matching characters)
                   6305:     - second element is an arrary ref containing the set of valid CODEs
                   6306:       that best fit the passed in CODE
                   6307: 
1.423     albertel 6308: =cut
                   6309: 
1.194     albertel 6310: sub scantron_get_closely_matching_CODEs {
                   6311:     my ($allcodes,$CODE)=@_;
                   6312:     my @CODEs;
                   6313:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6314: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6315:     }
                   6316: 
                   6317:     return ($#CODEs,$CODEs[-1]);
                   6318: }
                   6319: 
1.423     albertel 6320: =pod
                   6321: 
                   6322: =item get_codes
                   6323: 
1.424     albertel 6324:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6325:    set of remembered CODEs.
                   6326: 
                   6327:  Arguments:
                   6328:   $old_name - name of the set of remembered CODEs
                   6329:   $cdom     - domain of the course
                   6330:   $cnum     - internal course name
                   6331: 
                   6332:  Returns:
                   6333:   %allcodes - keys are the valid CODEs, values are all 1
                   6334: 
1.423     albertel 6335: =cut
                   6336: 
1.194     albertel 6337: sub get_codes {
1.280     foxr     6338:     my ($old_name, $cdom, $cnum) = @_;
                   6339:     if (!$old_name) {
                   6340: 	$old_name=$env{'form.scantron_CODElist'};
                   6341:     }
                   6342:     if (!$cdom) {
                   6343: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6344:     }
                   6345:     if (!$cnum) {
                   6346: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6347:     }
1.278     albertel 6348:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6349: 				    $cdom,$cnum);
                   6350:     my %allcodes;
                   6351:     if ($result{"type\0$old_name"} eq 'number') {
                   6352: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6353:     } else {
                   6354: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6355:     }
1.194     albertel 6356:     return %allcodes;
                   6357: }
                   6358: 
1.423     albertel 6359: =pod
                   6360: 
                   6361: =item scantron_validate_CODE
                   6362: 
1.424     albertel 6363:    Validates all scanlines in the selected file to not have any
                   6364:    invalid or underspecified CODEs and that none of the codes are
                   6365:    duplicated if this was requested.
                   6366: 
1.423     albertel 6367: =cut
                   6368: 
1.157     albertel 6369: sub scantron_validate_CODE {
                   6370:     my ($r,$currentphase) = @_;
1.257     albertel 6371:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6372:     if ($scantron_config{'CODElocation'} &&
                   6373: 	$scantron_config{'CODEstart'} &&
                   6374: 	$scantron_config{'CODElength'}) {
1.257     albertel 6375: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6376: 	    &FIXME_blow_up()
                   6377: 	}
                   6378:     } else {
                   6379: 	return (0,$currentphase+1);
                   6380:     }
                   6381:     
                   6382:     my %usedCODEs;
                   6383: 
1.194     albertel 6384:     my %allcodes=&get_codes();
1.186     albertel 6385: 
                   6386:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6387:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6388: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6389: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6390: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6391: 						 $scan_data);
                   6392: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6393: 	my $error=0;
1.224     albertel 6394: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6395: 	    &scantron_get_correction($r,$i,$scan_record,
                   6396: 				     \%scantron_config,
                   6397: 				     $line,'incorrectCODE',\%allcodes);
                   6398: 	    return(1,$currentphase);
                   6399: 	}
1.221     albertel 6400: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6401: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6402: 	    &scantron_get_correction($r,$i,$scan_record,
                   6403: 				     \%scantron_config,
1.194     albertel 6404: 				     $line,'incorrectCODE',\%allcodes);
                   6405: 	    return(1,$currentphase);
1.186     albertel 6406: 	}
1.214     albertel 6407: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6408: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6409: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6410: 	    &scantron_get_correction($r,$i,$scan_record,
                   6411: 				     \%scantron_config,
1.194     albertel 6412: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6413: 	    return(1,$currentphase);
1.186     albertel 6414: 	}
1.194     albertel 6415: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6416:     }
1.157     albertel 6417:     return (0,$currentphase+1);
                   6418: }
                   6419: 
1.423     albertel 6420: =pod
                   6421: 
                   6422: =item scantron_validate_doublebubble
                   6423: 
1.424     albertel 6424:    Validates all scanlines in the selected file to not have any
                   6425:    bubble lines with multiple bubbles marked.
                   6426: 
1.423     albertel 6427: =cut
                   6428: 
1.157     albertel 6429: sub scantron_validate_doublebubble {
                   6430:     my ($r,$currentphase) = @_;
                   6431:     #get student info
                   6432:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6433:     my %idmap=&username_to_idmap($classlist);
                   6434: 
                   6435:     #get scantron line setup
1.257     albertel 6436:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6437:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6438:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6439: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6440: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6441: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6442: 						 $scan_data);
                   6443: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6444: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6445: 				 'doublebubble',
                   6446: 				 $$scan_record{'scantron.doubleerror'});
                   6447:     	return (1,$currentphase);
                   6448:     }
                   6449:     return (0,$currentphase+1);
                   6450: }
                   6451: 
1.423     albertel 6452: =pod
                   6453: 
                   6454: =item scantron_get_maxbubble
                   6455: 
1.424     albertel 6456:    Returns the maximum number of bubble lines that are expected to
                   6457:    occur. Does this by walking the selected sequence rendering the
                   6458:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6459:    for what the current value of the problem counter is.
                   6460: 
                   6461:    Caches the result to $env{'form.scantron_maxbubble'}
                   6462: 
1.423     albertel 6463: =cut
                   6464: 
1.330     albertel 6465: sub scantron_get_maxbubble {    
1.257     albertel 6466:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6467: 	$env{'form.scantron_maxbubble'}) {
                   6468: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6469:     }
1.330     albertel 6470: 
1.191     albertel 6471:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6472:     my (undef,undef,$sequence)=
1.257     albertel 6473: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6474: 
1.191     albertel 6475:     my $map=$navmap->getResourceByUrl($sequence);
                   6476:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6477: 
                   6478:     &Apache::lonxml::clear_problem_counter();
                   6479: 
1.191     albertel 6480:     foreach my $resource (@resources) {
1.330     albertel 6481: 	my $result=&Apache::lonnet::ssi($resource->src(),
                   6482: 					('symb' => $resource->symb()));
1.191     albertel 6483:     }
                   6484:     &Apache::lonnet::delenv('scantron\.');
1.330     albertel 6485:     $env{'form.scantron_maxbubble'} =
                   6486: 	&Apache::lonxml::get_problem_counter()-1;
                   6487: 
1.257     albertel 6488:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6489: }
                   6490: 
1.423     albertel 6491: =pod
                   6492: 
                   6493: =item scantron_validate_missingbubbles
                   6494: 
1.424     albertel 6495:    Validates all scanlines in the selected file to not have any
                   6496:    bubble lines with missing bubbles that haven't been verified as missing.
                   6497: 
1.423     albertel 6498: =cut
                   6499: 
1.157     albertel 6500: sub scantron_validate_missingbubbles {
                   6501:     my ($r,$currentphase) = @_;
                   6502:     #get student info
                   6503:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6504:     my %idmap=&username_to_idmap($classlist);
                   6505: 
                   6506:     #get scantron line setup
1.257     albertel 6507:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6508:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6509:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6510:     if (!$max_bubble) { $max_bubble=2**31; }
                   6511:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6512: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6513: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6514: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6515: 						 $scan_data);
                   6516: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6517: 	my @to_correct;
                   6518: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6519: 	    if ($missing > $max_bubble) { next; }
                   6520: 	    push(@to_correct,$missing);
                   6521: 	}
                   6522: 	if (@to_correct) {
                   6523: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6524: 				     $line,'missingbubble',\@to_correct);
                   6525: 	    return (1,$currentphase);
                   6526: 	}
                   6527: 
                   6528:     }
                   6529:     return (0,$currentphase+1);
                   6530: }
                   6531: 
1.423     albertel 6532: =pod
                   6533: 
                   6534: =item scantron_process_students
                   6535: 
                   6536:    Routine that does the actual grading of the bubble sheet information.
                   6537: 
                   6538:    The parsed scanline hash is added to %env 
                   6539: 
                   6540:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6541:    foreach resource , with the form data of
                   6542: 
                   6543: 	'submitted'     =>'scantron' 
                   6544: 	'grade_target'  =>'grade',
                   6545: 	'grade_username'=> username of student
                   6546: 	'grade_domain'  => domain of student
                   6547: 	'grade_courseid'=> of course
                   6548: 	'grade_symb'    => symb of resource to grade
                   6549: 
                   6550:     This triggers a grading pass. The problem grading code takes care
                   6551:     of converting the bubbled letter information (now in %env) into a
                   6552:     valid submission.
                   6553: 
                   6554: =cut
                   6555: 
1.82      albertel 6556: sub scantron_process_students {
1.75      albertel 6557:     my ($r) = @_;
1.257     albertel 6558:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6559:     my ($symb)=&get_symb($r);
1.81      albertel 6560:     if (!$symb) {return '';}
1.324     albertel 6561:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6562: 
1.257     albertel 6563:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6564:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6565:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6566:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6567:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6568:     my $map=$navmap->getResourceByUrl($sequence);
                   6569:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6570: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6571:     my $result= <<SCANTRONFORM;
1.81      albertel 6572: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6573:   <input type="hidden" name="command" value="scantron_configphase" />
                   6574:   $default_form_data
                   6575: SCANTRONFORM
1.82      albertel 6576:     $r->print($result);
                   6577: 
                   6578:     my @delayqueue;
1.140     albertel 6579:     my %completedstudents;
                   6580:     
1.200     albertel 6581:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6582:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6583:  				    'Scantron Progress',$count,
1.195     albertel 6584: 				    'inline',undef,'scantronupload');
1.140     albertel 6585:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6586: 					  'Processing first student');
                   6587:     my $start=&Time::HiRes::time();
1.158     albertel 6588:     my $i=-1;
1.200     albertel 6589:     my ($uname,$udom,$started);
1.157     albertel 6590:     while ($i<$scanlines->{'count'}) {
                   6591:  	($uname,$udom)=('','');
                   6592:  	$i++;
1.200     albertel 6593:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6594:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 6595: 	if ($started) {
                   6596: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   6597: 						     'last student');
                   6598: 	}
                   6599: 	$started=1;
1.157     albertel 6600:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6601:  						 $scan_data);
                   6602:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   6603:  					      \%idmap,$i)) {
                   6604:   	    &scantron_add_delay(\@delayqueue,$line,
                   6605:  				'Unable to find a student that matches',1);
                   6606:  	    next;
                   6607:   	}
                   6608:  	if (exists $completedstudents{$uname}) {
                   6609:  	    &scantron_add_delay(\@delayqueue,$line,
                   6610:  				'Student '.$uname.' has multiple sheets',2);
                   6611:  	    next;
                   6612:  	}
                   6613:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 6614: 
                   6615: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 6616:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 6617: 
                   6618: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   6619: 	    &scantron_putfile($scanlines,$scan_data);
                   6620: 	}
1.161     albertel 6621: 	
                   6622: 	my $i=0;
1.83      albertel 6623: 	foreach my $resource (@resources) {
1.85      albertel 6624: 	    $i++;
1.193     albertel 6625: 	    my %form=('submitted'     =>'scantron',
                   6626: 		      'grade_target'  =>'grade',
                   6627: 		      'grade_username'=>$uname,
                   6628: 		      'grade_domain'  =>$udom,
1.257     albertel 6629: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 6630: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 6631: 	    if (exists($scan_record->{'scantron.CODE'})
                   6632: 		&& 
                   6633: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 6634: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 6635: 	    } else {
                   6636: 		$form{'CODE'}='';
1.193     albertel 6637: 	    }
                   6638: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 6639: 	    if ($result ne '') {
                   6640: 		&Apache::lonnet::logthis("scantron grading error -> $result");
1.257     albertel 6641: 		&Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
1.227     albertel 6642: 	    }
1.213     albertel 6643: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 6644: 	}
1.140     albertel 6645: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 6646: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 6647:     } continue {
1.330     albertel 6648: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 6649: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 6650:     }
1.140     albertel 6651:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 6652: #    my $lasttime = &Time::HiRes::time()-$start;
                   6653: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 6654: 
1.200     albertel 6655:     $r->print("</form>");
1.324     albertel 6656:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 6657:     return '';
1.75      albertel 6658: }
1.157     albertel 6659: 
1.423     albertel 6660: =pod
                   6661: 
                   6662: =item scantron_upload_scantron_data
                   6663: 
                   6664:     Creates the screen for adding a new bubble sheet data file to a course.
                   6665: 
                   6666: =cut
                   6667: 
1.157     albertel 6668: sub scantron_upload_scantron_data {
                   6669:     my ($r)=@_;
1.257     albertel 6670:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 6671:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 6672: 							  'domainid',
                   6673: 							  'coursename');
1.257     albertel 6674:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 6675: 						   'domainid');
1.324     albertel 6676:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 6677:     $r->print(<<UPLOAD);
                   6678: <script type="text/javascript" language="javascript">
                   6679:     function checkUpload(formname) {
                   6680: 	if (formname.upfile.value == "") {
                   6681: 	    alert("Please use the browse button to select a file from your local directory.");
                   6682: 	    return false;
                   6683: 	}
                   6684: 	formname.submit();
                   6685:     }
                   6686: </script>
                   6687: 
                   6688: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 6689: $default_form_data
1.181     albertel 6690: <table>
                   6691: <tr><td>$select_link </td></tr>
                   6692: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   6693: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   6694: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   6695: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   6696: </table>
1.157     albertel 6697: <input name='command' value='scantronupload_save' type='hidden' />
                   6698: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   6699: </form>
                   6700: UPLOAD
                   6701:     return '';
                   6702: }
                   6703: 
1.423     albertel 6704: =pod
                   6705: 
                   6706: =item scantron_upload_scantron_data_save
                   6707: 
                   6708:    Adds a provided bubble information data file to the course if user
                   6709:    has the correct privileges to do so.  
                   6710: 
                   6711: =cut
                   6712: 
1.157     albertel 6713: sub scantron_upload_scantron_data_save {
                   6714:     my($r)=@_;
1.324     albertel 6715:     my ($symb)=&get_symb($r,1);
1.182     albertel 6716:     my $doanotherupload=
                   6717: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   6718: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   6719: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   6720: 	'</form>'."\n";
1.257     albertel 6721:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 6722: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 6723: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 6724: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 6725: 	if ($symb) {
1.324     albertel 6726: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 6727: 	} else {
                   6728: 	    $r->print($doanotherupload);
                   6729: 	}
1.162     albertel 6730: 	return '';
                   6731:     }
1.257     albertel 6732:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       6733:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 6734:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 6735:     #FIXME
                   6736:     #copied from lonnet::userfileupload()
                   6737:     #make that function able to target a specified course
                   6738:     # Replace Windows backslashes by forward slashes
                   6739:     $fname=~s/\\/\//g;
                   6740:     # Get rid of everything but the actual filename
                   6741:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   6742:     # Replace spaces by underscores
                   6743:     $fname=~s/\s+/\_/g;
                   6744:     # Replace all other weird characters by nothing
                   6745:     $fname=~s/[^\w\.\-]//g;
                   6746:     # See if there is anything left
                   6747:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       6748:     my $uploadedfile=$fname;
1.157     albertel 6749:     $fname='scantron_orig_'.$fname;
1.257     albertel 6750:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 6751: 	$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 6752:     } else {
1.275     albertel 6753: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 6754: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 6755: 	    $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 6756: 	} else {
1.398     albertel 6757: 	    $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 6758: 	}
                   6759:     }
1.174     albertel 6760:     if ($symb) {
1.209     ng       6761: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 6762:     } else {
1.182     albertel 6763: 	$r->print($doanotherupload);
1.174     albertel 6764:     }
1.157     albertel 6765:     return '';
                   6766: }
                   6767: 
1.423     albertel 6768: =pod
                   6769: 
                   6770: =item valid_file
                   6771: 
1.424     albertel 6772:    Validates that the requested bubble data file exists in the course.
1.423     albertel 6773: 
                   6774: =cut
                   6775: 
1.202     albertel 6776: sub valid_file {
                   6777:     my ($requested_file)=@_;
                   6778:     foreach my $filename (sort(&scantron_filenames())) {
                   6779: 	if ($requested_file eq $filename) { return 1; }
                   6780:     }
                   6781:     return 0;
                   6782: }
                   6783: 
1.423     albertel 6784: =pod
                   6785: 
                   6786: =item scantron_download_scantron_data
                   6787: 
                   6788:    Shows a list of the three internal files (original, corrected,
                   6789:    skipped) for a specific bubble sheet data file that exists in the
                   6790:    course.
                   6791: 
                   6792: =cut
                   6793: 
1.202     albertel 6794: sub scantron_download_scantron_data {
                   6795:     my ($r)=@_;
1.324     albertel 6796:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 6797:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6798:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6799:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 6800:     if (! &valid_file($file)) {
                   6801: 	$r->print(<<ERROR);
                   6802: 	<p>
                   6803: 	    The requested file name was invalid.
                   6804:         </p>
                   6805: ERROR
1.324     albertel 6806: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 6807: 	return;
                   6808:     }
                   6809:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   6810:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   6811:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   6812:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   6813:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   6814:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   6815:     $r->print(<<DOWNLOAD);
                   6816:     <p>
                   6817: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   6818:     </p>
                   6819:     <p>
                   6820: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   6821:     </p>
                   6822:     <p>
                   6823: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   6824:     </p>
                   6825: DOWNLOAD
1.324     albertel 6826:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 6827:     return '';
                   6828: }
1.157     albertel 6829: 
1.423     albertel 6830: =pod
                   6831: 
                   6832: =back
                   6833: 
                   6834: =cut
                   6835: 
1.75      albertel 6836: #-------- end of section for handling grading scantron forms -------
                   6837: #
                   6838: #-------------------------------------------------------------------
                   6839: 
1.72      ng       6840: #-------------------------- Menu interface -------------------------
                   6841: #
                   6842: #--- Show a Grading Menu button - Calls the next routine ---
                   6843: sub show_grading_menu_form {
1.324     albertel 6844:     my ($symb)=@_;
1.125     ng       6845:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 6846: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 6847: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       6848: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   6849: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   6850: 	'</form>'."\n";
                   6851:     return $result;
                   6852: }
                   6853: 
1.77      ng       6854: # -- Retrieve choices for grading form
                   6855: sub savedState {
                   6856:     my %savedState = ();
1.257     albertel 6857:     if ($env{'form.saveState'}) {
                   6858: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       6859: 	    my ($key,$value) = split(/=/,$_,2);
                   6860: 	    $savedState{$key} = $value;
                   6861: 	}
                   6862:     }
                   6863:     return \%savedState;
                   6864: }
1.76      ng       6865: 
1.72      ng       6866: #--- Displays the main menu page -------
                   6867: sub gradingmenu {
                   6868:     my ($request) = @_;
1.324     albertel 6869:     my ($symb)=&get_symb($request);
1.72      ng       6870:     if (!$symb) {return '';}
1.76      ng       6871:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       6872: 
                   6873:     $request->print(<<GRADINGMENUJS);
                   6874: <script type="text/javascript" language="javascript">
1.116     ng       6875:     function checkChoice(formname,val,cmdx) {
                   6876: 	if (val <= 2) {
                   6877: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       6878: 	    var cmdsave = cmd;
1.116     ng       6879: 	} else {
                   6880: 	    cmd = cmdx;
1.118     ng       6881: 	    cmdsave = 'submission';
1.116     ng       6882: 	}
                   6883: 	formname.command.value = cmd;
1.118     ng       6884: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 6885: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       6886: 	if (val < 5) formname.submit();
                   6887: 	if (val == 5) {
1.72      ng       6888: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   6889: 	    formname.submit();
                   6890: 	}
1.238     albertel 6891: 	if (val < 7) formname.submit();
1.72      ng       6892:     }
                   6893: 
                   6894:     function checkReceiptNo(formname,nospace) {
                   6895: 	var receiptNo = formname.receipt.value;
                   6896: 	var checkOpt = false;
                   6897: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   6898: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   6899: 	if (checkOpt) {
                   6900: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   6901: 	    formname.receipt.value = "";
                   6902: 	    formname.receipt.focus();
                   6903: 	    return false;
                   6904: 	}
                   6905: 	return true;
                   6906:     }
                   6907: </script>
                   6908: GRADINGMENUJS
1.118     ng       6909:     &commonJSfunctions($request);
1.398     albertel 6910:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
1.324     albertel 6911:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       6912:     $result.=$table;
1.76      ng       6913:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       6914:     my $savedState = &savedState();
1.118     ng       6915:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       6916:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       6917:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       6918:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       6919: 
                   6920:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 6921: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       6922: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   6923: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       6924: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       6925: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       6926: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       6927: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   6928: 
1.326     albertel 6929:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   6930: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
1.72      ng       6931: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       6932: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   6933: 
1.326     albertel 6934:     $result.='<table width="100%" border="0">';
1.116     ng       6935:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.429     banghart 6936: 	'&nbsp;'.&mt('Select Section').': <select name="section" multiple="multiple" size="3">'."\n";
1.116     ng       6937:     if (ref($sections)) {
1.155     albertel 6938: 	foreach (sort (@$sections)) {
                   6939: 	    $result.='<option value="'.$_.'" '.
1.401     albertel 6940: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
1.155     albertel 6941: 	}
1.116     ng       6942:     }
1.401     albertel 6943:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.116     ng       6944: 
1.401     albertel 6945:     $result.=&mt('Student Status').':'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
1.72      ng       6946: 
1.116     ng       6947:     $result.='</td></tr>';
                   6948: 
1.288     albertel 6949:     $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
1.118     ng       6950: 	'<input type="radio" name="radioChoice" value="submission" '.
1.401     albertel 6951: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 6952: 	'</label> <select name="submitonly">'.
1.145     albertel 6953: 	'<option value="yes" '.
1.401     albertel 6954: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
1.301     albertel 6955: 	'<option value="queued" '.
1.401     albertel 6956: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
1.145     albertel 6957: 	'<option value="graded" '.
1.401     albertel 6958: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 6959: 	'<option value="incorrect" '.
1.401     albertel 6960: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 6961: 	'<option value="all" '.
1.401     albertel 6962: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       6963: 
1.116     ng       6964:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.288     albertel 6965: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.401     albertel 6966: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
1.288     albertel 6967: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       6968: 
1.118     ng       6969:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
1.288     albertel 6970: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.401     albertel 6971: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
1.288     albertel 6972: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       6973: 
1.116     ng       6974:     $result.='<tr bgcolor="#ffffe6"><td><br />'.
1.126     ng       6975: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       6976: 	'</td></tr></table>'."\n";
                   6977: 
                   6978:     $result.='</td><td valign="top">';
                   6979: 
1.326     albertel 6980:     $result.='<table width="100%" border="0">';
1.116     ng       6981:     $result.='<tr bgcolor="#ffffe6"><td>'.
1.184     www      6982: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   6983: 	' '.&mt('scores from file').' </td></tr>'."\n";
1.72      ng       6984: 
1.404     www      6985:     $result.='<tr bgcolor="#ffffe6"><td>'.
                   6986:         '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
                   6987:         ' '.&mt('clicker file').' </td></tr>'."\n";
1.400     www      6988: 
1.75      albertel 6989:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.116     ng       6990: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
1.184     www      6991: 	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
1.75      albertel 6992: 
1.257     albertel 6993:     if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
1.72      ng       6994: 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.184     www      6995: 	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   6996: 	    ' '.&mt('receipt').': '.
1.257     albertel 6997: 	    &Apache::lonnet::recprefix($env{'request.course.id'}).
1.326     albertel 6998: 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
1.72      ng       6999: 	    '</td></tr>'."\n";
                   7000:     } 
1.238     albertel 7001:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7002: 	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   7003: 	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
1.279     albertel 7004:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7005: 	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   7006: 	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
1.44      ng       7007: 
1.401     albertel 7008:     $result.='</table>'."\n".
1.72      ng       7009: 	'</td></tr></table>'."\n".
1.401     albertel 7010: 	'</td></tr></table></form>'."\n";
1.44      ng       7011:     return $result;
1.2       albertel 7012: }
                   7013: 
1.285     albertel 7014: sub reset_perm {
                   7015:     undef(%perm);
                   7016: }
                   7017: 
                   7018: sub init_perm {
                   7019:     &reset_perm();
1.300     albertel 7020:     foreach my $test_perm ('vgr','mgr','opa') {
                   7021: 
                   7022: 	my $scope = $env{'request.course.id'};
                   7023: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7024: 
                   7025: 	    $scope .= '/'.$env{'request.course.sec'};
                   7026: 	    if ( $perm{$test_perm}=
                   7027: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7028: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7029: 	    } else {
                   7030: 		delete($perm{$test_perm});
                   7031: 	    }
1.285     albertel 7032: 	}
                   7033:     }
                   7034: }
                   7035: 
1.400     www      7036: sub gather_clicker_ids {
1.408     albertel 7037:     my %clicker_ids;
1.400     www      7038: 
                   7039:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7040: 
                   7041:     # Set up a couple variables.
1.407     albertel 7042:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7043:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.400     www      7044: 
1.407     albertel 7045:     foreach my $student (keys(%$classlist)) {
1.400     www      7046: 
1.407     albertel 7047:         my $username = $classlist->{$student}->[$username_idx];
                   7048:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7049:         my $clickers =
1.408     albertel 7050: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7051:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7052:             $id=~s/^[\#0]+//;
1.421     www      7053:             $id=~s/[\-\:]//g;
1.407     albertel 7054:             if (exists($clicker_ids{$id})) {
1.408     albertel 7055: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7056:             } else {
1.408     albertel 7057: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7058:             }
                   7059:         }
                   7060:     }
1.407     albertel 7061:     return %clicker_ids;
1.400     www      7062: }
                   7063: 
1.402     www      7064: sub gather_adv_clicker_ids {
1.408     albertel 7065:     my %clicker_ids;
1.402     www      7066:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7067:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7068:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7069:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7070:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7071:             my ($puname,$pudom)=split(/\:/,$person);
                   7072:             my $clickers =
1.408     albertel 7073: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7074:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7075: 		$id=~s/^[\#0]+//;
1.421     www      7076:                 $id=~s/[\-\:]//g;
1.408     albertel 7077: 		if (exists($clicker_ids{$id})) {
                   7078: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7079: 		} else {
                   7080: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7081: 		}
1.405     www      7082:             }
1.402     www      7083:         }
                   7084:     }
1.407     albertel 7085:     return %clicker_ids;
1.402     www      7086: }
                   7087: 
1.413     www      7088: sub clicker_grading_parameters {
                   7089:     return ('gradingmechanism' => 'scalar',
                   7090:             'upfiletype' => 'scalar',
                   7091:             'specificid' => 'scalar',
                   7092:             'pcorrect' => 'scalar',
                   7093:             'pincorrect' => 'scalar');
                   7094: }
                   7095: 
1.400     www      7096: sub process_clicker {
                   7097:     my ($r)=@_;
                   7098:     my ($symb)=&get_symb($r);
                   7099:     if (!$symb) {return '';}
                   7100:     my $result=&checkforfile_js();
                   7101:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7102:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7103:     $result.=$table;
                   7104:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7105:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7106:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7107:         '.</b></td></tr>'."\n";
                   7108:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7109: # Attempt to restore parameters from last session, set defaults if not present
                   7110:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7111:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7112:                                                  \%Saveable_Parameters);
                   7113:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7114:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7115:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7116:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7117: 
                   7118:     my %checked;
                   7119:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7120:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7121:           $checked{$gradingmechanism}="checked='checked'";
                   7122:        }
                   7123:     }
                   7124: 
1.400     www      7125:     my $upload=&mt("Upload File");
                   7126:     my $type=&mt("Type");
1.402     www      7127:     my $attendance=&mt("Award points just for participation");
                   7128:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7129:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7130:     my $pcorrect=&mt("Percentage points for correct solution");
                   7131:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7132:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7133: 						   ('iclicker' => 'i>clicker',
                   7134:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7135:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7136:     $result.=<<ENDUPFORM;
1.402     www      7137: <script type="text/javascript">
                   7138: function sanitycheck() {
                   7139: // Accept only integer percentages
                   7140:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7141:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7142: // Find out grading choice
                   7143:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7144:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7145:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7146:       }
                   7147:    }
                   7148: // By default, new choice equals user selection
                   7149:    newgradingchoice=gradingchoice;
                   7150: // Not good to give more points for false answers than correct ones
                   7151:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7152:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7153:    }
                   7154: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7155:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7156:       document.forms.gradesupload.pcorrect.value=100;
                   7157:       document.forms.gradesupload.pincorrect.value=100;
                   7158:    }
                   7159: // If the values are different, cannot be attendance only
                   7160:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7161:        (gradingchoice=='attendance')) {
                   7162:        newgradingchoice='personnel';
                   7163:    }
                   7164: // Change grading choice to new one
                   7165:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7166:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7167:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7168:       } else {
                   7169:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7170:       }
                   7171:    }
                   7172: // Remember the old state
                   7173:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7174: }
                   7175: </script>
1.400     www      7176: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7177: <input type="hidden" name="symb" value="$symb" />
                   7178: <input type="hidden" name="command" value="processclickerfile" />
                   7179: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7180: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7181: <input type="file" name="upfile" size="50" />
                   7182: <br /><label>$type: $selectform</label>
1.413     www      7183: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
                   7184: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
                   7185: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
1.414     www      7186: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7187: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7188: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7189: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7190: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7191: </form>
                   7192: ENDUPFORM
                   7193:     $result.='</td></tr></table>'."\n".
                   7194:              '</td></tr></table><br /><br />'."\n";
                   7195:     $result.=&show_grading_menu_form($symb);
                   7196:     return $result;
                   7197: }
                   7198: 
                   7199: sub process_clicker_file {
                   7200:     my ($r)=@_;
                   7201:     my ($symb)=&get_symb($r);
                   7202:     if (!$symb) {return '';}
1.413     www      7203: 
                   7204:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7205:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7206:                                               \%Saveable_Parameters);
                   7207: 
1.400     www      7208:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7209:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7210: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7211: 	return $result.&show_grading_menu_form($symb);
1.404     www      7212:     }
1.407     albertel 7213:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7214:     my %correct_ids;
1.404     www      7215:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7216: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7217:     }
                   7218:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7219: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7220: 	   $correct_id=~tr/a-z/A-Z/;
                   7221: 	   $correct_id=~s/\s//gs;
                   7222: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7223:            $correct_id=~s/[\-\:]//g;
1.414     www      7224:            if ($correct_id) {
                   7225: 	      $correct_ids{$correct_id}='specified';
                   7226:            }
                   7227:         }
1.400     www      7228:     }
1.404     www      7229:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7230: 	$result.=&mt('Score based on attendance only');
1.404     www      7231:     } else {
1.408     albertel 7232: 	my $number=0;
1.411     www      7233: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7234: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7235: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7236: 	    if ($correct_ids{$id} eq 'specified') {
                   7237: 		$result.=&mt('specified');
                   7238: 	    } else {
                   7239: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7240: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7241: 	    }
                   7242: 	    $number++;
                   7243: 	}
1.411     www      7244:         $result.="</p>\n";
1.408     albertel 7245: 	if ($number==0) {
                   7246: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7247: 	    return $result.&show_grading_menu_form($symb);
                   7248: 	}
1.404     www      7249:     }
1.405     www      7250:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7251:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7252: 		     '<span class="LC_error">',
                   7253: 		     '</span>',
                   7254: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7255:         return $result.&show_grading_menu_form($symb);
                   7256:     }
1.410     www      7257: 
                   7258: # Were able to get all the info needed, now analyze the file
                   7259: 
1.411     www      7260:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7261:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7262:     my $heading=&mt('Scanning clicker file');
                   7263:     $result.=(<<ENDHEADER);
                   7264: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7265: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7266: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7267: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7268: <input type="hidden" name="symb" value="$symb" />
                   7269: <input type="hidden" name="command" value="assignclickergrades" />
                   7270: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7271: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7272: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7273: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7274: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7275: ENDHEADER
1.408     albertel 7276:     my %responses;
                   7277:     my @questiontitles;
1.405     www      7278:     my $errormsg='';
                   7279:     my $number=0;
                   7280:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7281: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7282:     }
1.419     www      7283:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7284:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7285:     }
1.411     www      7286:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7287:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   7288:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7289:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7290:              '<br />';
1.414     www      7291: # Remember Question Titles
                   7292: # FIXME: Possibly need delimiter other than ":"
                   7293:     for (my $i=0;$i<$number;$i++) {
                   7294:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7295:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7296:     }
1.411     www      7297:     my $correct_count=0;
                   7298:     my $student_count=0;
                   7299:     my $unknown_count=0;
1.414     www      7300: # Match answers with usernames
                   7301: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7302:     foreach my $id (keys(%responses)) {
1.410     www      7303:        if ($correct_ids{$id}) {
1.414     www      7304:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7305:           $correct_count++;
1.410     www      7306:        } elsif ($clicker_ids{$id}) {
                   7307:           $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7308:           $student_count++;
1.410     www      7309:        } else {
1.411     www      7310:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7311:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7312:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7313:                    "\n".&mt("Domain").": ".
                   7314:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7315:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7316:           $unknown_count++;
1.410     www      7317:        }
1.405     www      7318:     }
1.412     www      7319:     $result.='<hr />'.
                   7320:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7321:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7322:        if ($correct_count==0) {
                   7323:           $errormsg.="Found no correct answers answers for grading!";
                   7324:        } elsif ($correct_count>1) {
1.414     www      7325:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7326:        }
                   7327:     }
1.428     www      7328:     if ($number<1) {
                   7329:        $errormsg.="Found no questions.";
                   7330:     }
1.412     www      7331:     if ($errormsg) {
                   7332:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7333:     } else {
                   7334:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7335:     }
                   7336:     $result.='</form></td></tr></table>'."\n".
1.410     www      7337:              '</td></tr></table><br /><br />'."\n";
1.404     www      7338:     return $result.&show_grading_menu_form($symb);
1.400     www      7339: }
                   7340: 
1.405     www      7341: sub iclicker_eval {
1.406     www      7342:     my ($questiontitles,$responses)=@_;
1.405     www      7343:     my $number=0;
                   7344:     my $errormsg='';
                   7345:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7346:         my %components=&Apache::loncommon::record_sep($line);
                   7347:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7348: 	if ($entries[0] eq 'Question') {
                   7349: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7350: 		$$questiontitles[$number]=$entries[$i];
                   7351: 		$number++;
                   7352: 	    }
                   7353: 	}
                   7354: 	if ($entries[0]=~/^\#/) {
                   7355: 	    my $id=$entries[0];
                   7356: 	    my @idresponses;
                   7357: 	    $id=~s/^[\#0]+//;
                   7358: 	    for (my $i=0;$i<$number;$i++) {
                   7359: 		my $idx=3+$i*6;
                   7360: 		push(@idresponses,$entries[$idx]);
                   7361: 	    }
                   7362: 	    $$responses{$id}=join(',',@idresponses);
                   7363: 	}
1.405     www      7364:     }
                   7365:     return ($errormsg,$number);
                   7366: }
                   7367: 
1.419     www      7368: sub interwrite_eval {
                   7369:     my ($questiontitles,$responses)=@_;
                   7370:     my $number=0;
                   7371:     my $errormsg='';
1.420     www      7372:     my $skipline=1;
                   7373:     my $questionnumber=0;
                   7374:     my %idresponses=();
1.419     www      7375:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   7376:         my %components=&Apache::loncommon::record_sep($line);
                   7377:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      7378:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   7379:         if ($entries[1] eq 'Response') { $skipline=1; }
                   7380:         next if $skipline;
                   7381:         if ($entries[0]!=$questionnumber) {
                   7382:            $questionnumber=$entries[0];
                   7383:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   7384:            $number++;
1.419     www      7385:         }
1.420     www      7386:         my $id=$entries[4];
                   7387:         $id=~s/^[\#0]+//;
1.421     www      7388:         $id=~s/^v\d*\://i;
                   7389:         $id=~s/[\-\:]//g;
1.420     www      7390:         $idresponses{$id}[$number]=$entries[6];
                   7391:     }
                   7392:     foreach my $id (keys %idresponses) {
                   7393:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   7394:        $$responses{$id}=~s/^\s*\,//;
1.419     www      7395:     }
                   7396:     return ($errormsg,$number);
                   7397: }
                   7398: 
1.414     www      7399: sub assign_clicker_grades {
                   7400:     my ($r)=@_;
                   7401:     my ($symb)=&get_symb($r);
                   7402:     if (!$symb) {return '';}
1.416     www      7403: # See which part we are saving to
                   7404:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   7405: # FIXME: This should probably look for the first handgradeable part
                   7406:     my $part=$$partlist[0];
                   7407: # Start screen output
1.414     www      7408:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      7409: 
1.414     www      7410:     my $heading=&mt('Assigning grades based on clicker file');
                   7411:     $result.=(<<ENDHEADER);
                   7412: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7413: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7414: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7415: ENDHEADER
                   7416: # Get correct result
                   7417: # FIXME: Possibly need delimiter other than ":"
                   7418:     my @correct=();
1.415     www      7419:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   7420:     my $number=$env{'form.number'};
                   7421:     if ($gradingmechanism ne 'attendance') {
1.414     www      7422:        foreach my $key (keys(%env)) {
                   7423:           if ($key=~/^form\.correct\:/) {
                   7424:              my @input=split(/\,/,$env{$key});
                   7425:              for (my $i=0;$i<=$#input;$i++) {
                   7426:                  if (($correct[$i]) && ($input[$i]) &&
                   7427:                      ($correct[$i] ne $input[$i])) {
                   7428:                     $result.='<br /><span class="LC_warning">'.
                   7429:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   7430:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   7431:                  } elsif ($input[$i]) {
                   7432:                     $correct[$i]=$input[$i];
                   7433:                  }
                   7434:              }
                   7435:           }
                   7436:        }
1.415     www      7437:        for (my $i=0;$i<$number;$i++) {
1.414     www      7438:           if (!$correct[$i]) {
                   7439:              $result.='<br /><span class="LC_error">'.
                   7440:                       &mt('No correct result given for question "[_1]"!',
                   7441:                           $env{'form.question:'.$i}).'</span>';
                   7442:           }
                   7443:        }
                   7444:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   7445:     }
                   7446: # Start grading
1.415     www      7447:     my $pcorrect=$env{'form.pcorrect'};
                   7448:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      7449:     my $storecount=0;
1.415     www      7450:     foreach my $key (keys(%env)) {
1.420     www      7451:        my $user='';
1.415     www      7452:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      7453:           $user=$1;
                   7454:        }
                   7455:        if ($key=~/^form\.unknown\:(.*)$/) {
                   7456:           my $id=$1;
                   7457:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   7458:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
                   7459:           }
                   7460:        }
                   7461:        if ($user) { 
1.415     www      7462:           my @answer=split(/\,/,$env{$key});
                   7463:           my $sum=0;
                   7464:           for (my $i=0;$i<$number;$i++) {
                   7465:              if ($answer[$i]) {
                   7466:                 if ($gradingmechanism eq 'attendance') {
                   7467:                    $sum+=$pcorrect;
                   7468:                 } else {
                   7469:                    if ($answer[$i] eq $correct[$i]) {
                   7470:                       $sum+=$pcorrect;
                   7471:                    } else {
                   7472:                       $sum+=$pincorrect;
                   7473:                    }
                   7474:                 }
                   7475:              }
                   7476:           }
1.416     www      7477:           my $ave=$sum/(100*$number);
                   7478: # Store
                   7479:           my ($username,$domain)=split(/\:/,$user);
                   7480:           my %grades=();
                   7481:           $grades{"resource.$part.solved"}='correct_by_override';
                   7482:           $grades{"resource.$part.awarded"}=$ave;
                   7483:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   7484:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   7485:                                                  $env{'request.course.id'},
                   7486:                                                  $domain,$username);
                   7487:           if ($returncode ne 'ok') {
                   7488:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   7489:           } else {
                   7490:              $storecount++;
                   7491:           }
1.415     www      7492:        }
                   7493:     }
                   7494: # We are done
1.416     www      7495:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   7496:              '</td></tr></table>'."\n".
1.414     www      7497:              '</td></tr></table><br /><br />'."\n";
                   7498:     return $result.&show_grading_menu_form($symb);
                   7499: }
                   7500: 
1.1       albertel 7501: sub handler {
1.41      ng       7502:     my $request=$_[0];
1.102     albertel 7503: 
1.285     albertel 7504:     &reset_perm();
1.257     albertel 7505:     if ($env{'browser.mathml'}) {
1.141     www      7506: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       7507:     } else {
1.141     www      7508: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       7509:     }
                   7510:     $request->send_http_header;
1.44      ng       7511:     return '' if $request->header_only;
1.41      ng       7512:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 7513:     my $symb=&get_symb($request,1);
1.160     albertel 7514:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   7515:     my $command=$commands[0];
                   7516:     if ($#commands > 0) {
                   7517: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   7518:     }
1.353     albertel 7519:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 7520:     if ($symb eq '' && $command eq '') {
1.257     albertel 7521: 	if ($env{'user.adv'}) {
                   7522: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   7523: 		($env{'form.codethree'})) {
                   7524: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   7525: 		    $env{'form.codethree'};
1.41      ng       7526: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   7527: 		    &Apache::lonnet::checkin($token);
                   7528: 		if ($tsymb) {
1.137     albertel 7529: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       7530: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 7531: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   7532: 					  ('grade_username' => $tuname,
                   7533: 					   'grade_domain' => $tudom,
                   7534: 					   'grade_courseid' => $tcrsid,
                   7535: 					   'grade_symb' => $tsymb)));
1.41      ng       7536: 		    } else {
1.45      ng       7537: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 7538: 		    }
1.41      ng       7539: 		} else {
1.45      ng       7540: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       7541: 		}
1.14      www      7542: 	    } else {
1.41      ng       7543: 		$request->print(&Apache::lonxml::tokeninputfield());
                   7544: 	    }
                   7545: 	}
                   7546:     } else {
1.285     albertel 7547: 	&init_perm();
1.430     banghart 7548: #	&Apache::lonnet::logthis("command is $command");
                   7549: #	foreach my $key (keys %perm) {
                   7550: #	    &Apache::lonnet::logthis("a key is $key");
                   7551: #	}
1.104     albertel 7552: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 7553: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 7554: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       7555: 	    &pickStudentPage($request);
1.103     albertel 7556: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       7557: 	    &displayPage($request);
1.104     albertel 7558: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       7559: 	    &updateGradeByPage($request);
1.104     albertel 7560: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       7561: 	    &processGroup($request);
1.104     albertel 7562: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.41      ng       7563: 	    $request->print(&gradingmenu($request));
1.104     albertel 7564: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       7565: 	    $request->print(&viewgrades($request));
1.104     albertel 7566: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       7567: 	    $request->print(&processHandGrade($request));
1.106     albertel 7568: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       7569: 	    $request->print(&editgrades($request));
1.106     albertel 7570: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       7571: 	    $request->print(&verifyreceipt($request));
1.400     www      7572:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   7573:             $request->print(&process_clicker($request));
                   7574:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   7575:             $request->print(&process_clicker_file($request));
1.414     www      7576:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   7577:             $request->print(&assign_clicker_grades($request));
1.106     albertel 7578: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       7579: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 7580: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       7581: 	    $request->print(&csvupload($request));
1.106     albertel 7582: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       7583: 	    $request->print(&csvuploadmap($request));
1.246     albertel 7584: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 7585: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 7586: 		$request->print(&csvuploadoptions($request));
1.41      ng       7587: 	    } else {
1.257     albertel 7588: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   7589: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       7590: 		} else {
1.257     albertel 7591: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       7592: 		}
                   7593: 		$request->print(&csvuploadmap($request));
                   7594: 	    }
1.246     albertel 7595: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   7596: 	    $request->print(&csvuploadassign($request));
1.106     albertel 7597: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 7598: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 7599:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   7600:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 7601: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   7602: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 7603: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 7604: 	    $request->print(&scantron_process_students($request));
1.157     albertel 7605:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 7606:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   7607: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 7608:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 7609:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 7610:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   7611: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 7612:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 7613:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 7614: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 7615:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 7616: 	} elsif ($command) {
1.157     albertel 7617: 	    $request->print("Access Denied ($command)");
1.26      albertel 7618: 	}
1.2       albertel 7619:     }
1.353     albertel 7620:     $request->print(&Apache::loncommon::end_page());
1.44      ng       7621:     return '';
                   7622: }
                   7623: 
1.1       albertel 7624: 1;
                   7625: 
1.13      albertel 7626: __END__;

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