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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.428   ! www         4: # $Id: grades.pm,v 1.427 2007/08/10 20:12:31 albertel Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: package Apache::grades;
                     30: use strict;
                     31: use Apache::style;
                     32: use Apache::lonxml;
                     33: use Apache::lonnet;
1.3       albertel   34: use Apache::loncommon;
1.112     ng         35: use Apache::lonhtmlcommon;
1.68      ng         36: use Apache::lonnavmaps;
1.1       albertel   37: use Apache::lonhomework;
1.55      matthew    38: use Apache::loncoursedata;
1.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.257     albertel 2974:     if ($env{'form.section'} eq 'all') {
1.126     ng       2975: 	$sectionClass='Class </h3>';
1.257     albertel 2976:     } elsif ($env{'form.section'} eq 'none') {
1.126     ng       2977: 	$sectionClass='Students in no Section </h3>';
1.52      albertel 2978:     } else {
1.257     albertel 2979: 	$sectionClass='Students in Section '.$env{'form.section'}.'</h3>';
1.52      albertel 2980:     }
1.126     ng       2981:     $result.='<h3>Assign Common Grade To '.$sectionClass;
1.52      albertel 2982:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   2983: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       2984:     #radio buttons/text box for assigning points for a section or class.
                   2985:     #handles different parts of a problem
1.375     albertel 2986:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       2987:     my %weight = ();
                   2988:     my $ctsparts = 0;
1.41      ng       2989:     $result.='<table border="0">';
1.45      ng       2990:     my %seen = ();
1.375     albertel 2991:     my @part_response_id = &flatten_responseType($responseType);
                   2992:     foreach my $part_response_id (@part_response_id) {
                   2993:     	my ($partid,$respid) = @{ $part_response_id };
                   2994: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       2995: 	next if $seen{$partid};
                   2996: 	$seen{$partid}++;
1.375     albertel 2997: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       2998: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   2999: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3000: 
1.44      ng       3001: 	$result.='<input type="hidden" name="partid_'.
                   3002: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3003: 	$result.='<input type="hidden" name="weight_'.
                   3004: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3005: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 3006: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3007: 	$result.='<table border="0"><tr>';  
1.41      ng       3008: 	my $ctr = 0;
1.42      ng       3009: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3010: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3011: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3012: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3013: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3014: 	    $ctr++;
                   3015: 	}
                   3016: 	$result.='</tr></table>';
1.44      ng       3017: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3018: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3019: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3020: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   3021: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3022: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3023: 		$weight{$partid}.')"> '.
1.401     albertel 3024: 	    '<option selected="selected"> </option>'.
1.125     ng       3025: 	    '<option>excused</option>'.
1.265     www      3026: 	    '<option>reset status</option></select></td>'.
1.266     albertel 3027:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       3028: 	$ctsparts++;
1.41      ng       3029:     }
1.52      albertel 3030:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   3031: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3032:     $result.='<input type="button" value="Revert to Default" '.
1.417     albertel 3033: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
1.41      ng       3034: 
1.44      ng       3035:     #table listing all the students in a section/class
                   3036:     #header of table
1.126     ng       3037:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       3038:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       3039: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       3040: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 3041:     my (@parts) = sort(&getpartlist($symb));
                   3042:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3043:     my @partids = ();
1.41      ng       3044:     foreach my $part (@parts) {
                   3045: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3046: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3047: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3048: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3049:         push(@partids, $partid);
1.324     albertel 3050: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3051: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 3052: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   3053: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       3054: 	    next;
1.207     albertel 3055: 	} else {
                   3056: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3057: 	}
1.53      albertel 3058: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 3059: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       3060:     }
                   3061:     $result.='</tr>';
1.44      ng       3062: 
1.270     albertel 3063:     my %last_resets = 
                   3064: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3065: 
1.41      ng       3066:     #get info for each student
1.44      ng       3067:     #list all the students - with points and grade status
1.257     albertel 3068:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3069:     my $ctr = 0;
1.294     albertel 3070:     foreach (sort 
                   3071: 	     {
                   3072: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3073: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3074: 		 }
                   3075: 		 return $a cmp $b;
                   3076: 	     } (keys(%$fullname))) {
1.126     ng       3077: 	$ctr++;
1.324     albertel 3078: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3079: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3080:     }
                   3081:     $result.='</table></td></tr></table>';
                   3082:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3083:     $result.='<input type="button" value="Save" '.
1.417     albertel 3084: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3085:     if (scalar(%$fullname) eq 0) {
                   3086: 	my $colspan=3+scalar(@parts);
1.398     albertel 3087: 	$result='<span class="LC_warning">There are no students in section "'.$env{'form.section'}.
                   3088: 	    '" with enrollment status "'.$env{'form.Status'}.'" to modify or grade.</span>';
1.96      albertel 3089:     }
1.324     albertel 3090:     $result.=&show_grading_menu_form($symb);
1.41      ng       3091:     return $result;
                   3092: }
                   3093: 
1.44      ng       3094: #--- call by previous routine to display each student
1.41      ng       3095: sub viewstudentgrade {
1.324     albertel 3096:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3097:     my ($uname,$udom) = split(/:/,$student);
                   3098:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3099:     my %aggregates = (); 
1.233     albertel 3100:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3101: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3102: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3103: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3104: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3105: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3106:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3107:     foreach my $apart (@$parts) {
                   3108: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3109: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3110:         $result.='<td align="center">';
1.269     raeburn  3111:         my ($aggtries,$totaltries);
                   3112:         unless (exists($aggregates{$part})) {
1.270     albertel 3113: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3114: 
                   3115: 	    $aggtries = $totaltries;
1.269     raeburn  3116:             if ($$last_resets{$part}) {  
1.270     albertel 3117:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3118: 					   $part);
                   3119:             }
1.269     raeburn  3120:             $result.='<input type="hidden" name="'.
                   3121:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3122:             $result.='<input type="hidden" name="'.
                   3123:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3124:             $aggregates{$part} = 1;
                   3125:         }
1.41      ng       3126: 	if ($type eq 'awarded') {
1.320     albertel 3127: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3128: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3129: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3130: 	    $result.='<input type="text" name="'.
1.89      albertel 3131: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3132: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3133: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3134: 	} elsif ($type eq 'solved') {
                   3135: 	    my ($status,$foo)=split(/_/,$score,2);
                   3136: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3137: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3138: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3139: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3140: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3141: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3142: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3143: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3144: 	    $result.='<option>reset status</option>';
1.126     ng       3145: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3146: 	} else {
                   3147: 	    $result.='<input type="hidden" name="'.
                   3148: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3149: 		    "\n";
1.233     albertel 3150: 	    $result.='<input type="text" name="'.
1.122     ng       3151: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3152: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3153: 	}
                   3154:     }
                   3155:     $result.='</tr>';
                   3156:     return $result;
1.38      ng       3157: }
                   3158: 
1.44      ng       3159: #--- change scores for all the students in a section/class
                   3160: #    record does not get update if unchanged
1.38      ng       3161: sub editgrades {
1.41      ng       3162:     my ($request) = @_;
                   3163: 
1.324     albertel 3164:     my $symb=&get_symb($request);
1.398     albertel 3165:     my $title='<h3><span class="LC_info">Current Grade Status</span></h3>';
                   3166:     $title.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4><br />'."\n";
                   3167:     $title.='<h4><b>Section: </b>'.$env{'form.section'}.'</h4>'."\n";
1.126     ng       3168: 
1.44      ng       3169:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3170:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3171: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3172: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3173: 
                   3174:     my %scoreptr = (
                   3175: 		    'correct'  =>'correct_by_override',
                   3176: 		    'incorrect'=>'incorrect_by_override',
                   3177: 		    'excused'  =>'excused',
                   3178: 		    'ungraded' =>'ungraded_attempted',
                   3179: 		    'nothing'  => '',
                   3180: 		    );
1.257     albertel 3181:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3182: 
1.44      ng       3183:     my (@partid);
                   3184:     my %weight = ();
1.54      albertel 3185:     my %columns = ();
1.44      ng       3186:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3187: 
1.324     albertel 3188:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3189:     my $header;
1.257     albertel 3190:     while ($ctr < $env{'form.totalparts'}) {
                   3191: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3192: 	push @partid,$partid;
1.257     albertel 3193: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3194: 	$ctr++;
1.54      albertel 3195:     }
1.324     albertel 3196:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3197:     foreach my $partid (@partid) {
                   3198: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3199: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3200: 	$columns{$partid}=2;
                   3201: 	foreach my $stores (@parts) {
                   3202: 	    my ($part,$type) = &split_part_type($stores);
                   3203: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3204: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3205: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3206: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3207: 	    $display =~ s/Number of Attempts/Tries/;
                   3208: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3209: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3210: 	    $columns{$partid}+=2;
                   3211: 	}
                   3212:     }
                   3213:     foreach my $partid (@partid) {
1.324     albertel 3214: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3215: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3216: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3217: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3218: 
1.44      ng       3219:     }
                   3220:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3221:     $result .= $header;
1.44      ng       3222:     $result .= '</tr>'."\n";
1.93      albertel 3223:     my $noupdate;
1.126     ng       3224:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3225:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3226: 	my $line;
1.257     albertel 3227: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3228: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3229: 	my %newrecord;
                   3230: 	my $updateflag = 0;
1.281     albertel 3231: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3232: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3233: 	if (!&canmodify($usec)) {
1.126     ng       3234: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3235: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3236: 	    next;
                   3237: 	}
1.269     raeburn  3238:         my %aggregate = ();
                   3239:         my $aggregateflag = 0;
1.281     albertel 3240: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3241: 	foreach (@partid) {
1.257     albertel 3242: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3243: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3244: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3245: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3246: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3247: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3248: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3249: 	    my $score;
                   3250: 	    if ($partial eq '') {
1.257     albertel 3251: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3252: 	    } elsif ($partial > 0) {
                   3253: 		$score = 'correct_by_override';
                   3254: 	    } elsif ($partial == 0) {
                   3255: 		$score = 'incorrect_by_override';
                   3256: 	    }
1.257     albertel 3257: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3258: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3259: 
1.292     albertel 3260: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3261: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3262: 	    if ($dropMenu eq 'reset status' &&
                   3263: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3264: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3265: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3266: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3267: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3268: 		$updateflag = 1;
1.269     raeburn  3269:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3270:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3271:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3272:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3273:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3274:                     $aggregateflag = 1;
                   3275:                 }
1.139     albertel 3276: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3277: 		$updateflag = 1;
                   3278: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3279: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3280: 		$rec_update++;
1.125     ng       3281: 	    }
                   3282: 
1.93      albertel 3283: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3284: 		'<td align="center">'.$awarded.
                   3285: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3286: 
1.54      albertel 3287: 
                   3288: 	    my $partid=$_;
                   3289: 	    foreach my $stores (@parts) {
                   3290: 		my ($part,$type) = &split_part_type($stores);
                   3291: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3292: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3293: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3294: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3295: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3296: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3297: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3298: 		    $updateflag=1;
                   3299: 		}
1.93      albertel 3300: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3301: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3302: 	    }
1.44      ng       3303: 	}
1.93      albertel 3304: 	$line.='</tr>'."\n";
1.301     albertel 3305: 
                   3306: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3307: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3308: 
1.44      ng       3309: 	if ($updateflag) {
                   3310: 	    $count++;
1.257     albertel 3311: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3312: 				    $udom,$uname);
1.301     albertel 3313: 
                   3314: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3315: 					      $cnum,$udom,$uname)) {
                   3316: 		# need to figure out if should be in queue.
                   3317: 		my %record =  
                   3318: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3319: 					     $udom,$uname);
                   3320: 		my $all_graded = 1;
                   3321: 		my $none_graded = 1;
                   3322: 		foreach my $part (@parts) {
                   3323: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3324: 			$all_graded = 0;
                   3325: 		    } else {
                   3326: 			$none_graded = 0;
                   3327: 		    }
                   3328: 		}
                   3329: 
                   3330: 		if ($all_graded || $none_graded) {
                   3331: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3332: 							   $symb,$cdom,$cnum,
                   3333: 							   $udom,$uname);
                   3334: 		}
                   3335: 	    }
                   3336: 
1.126     ng       3337: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3338: 	    $updateCtr++;
1.93      albertel 3339: 	} else {
1.126     ng       3340: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3341: 	    $noupdateCtr++;
1.44      ng       3342: 	}
1.269     raeburn  3343:         if ($aggregateflag) {
                   3344:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3345: 				  $cdom,$cnum);
1.269     raeburn  3346:         }
1.93      albertel 3347:     }
                   3348:     if ($noupdate) {
1.126     ng       3349: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3350: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3351: 	$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       3352:     }
1.72      ng       3353:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3354: 	&show_grading_menu_form ($symb);
1.125     ng       3355:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3356: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3357: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3358:     return $title.$msg.$result;
1.5       albertel 3359: }
1.54      albertel 3360: 
                   3361: sub split_part_type {
                   3362:     my ($partstr) = @_;
                   3363:     my ($temp,@allparts)=split(/_/,$partstr);
                   3364:     my $type=pop(@allparts);
                   3365:     my $part=join('.',@allparts);
                   3366:     return ($part,$type);
                   3367: }
                   3368: 
1.44      ng       3369: #------------- end of section for handling grading by section/class ---------
                   3370: #
                   3371: #----------------------------------------------------------------------------
                   3372: 
1.5       albertel 3373: 
1.44      ng       3374: #----------------------------------------------------------------------------
                   3375: #
                   3376: #-------------------------- Next few routines handles grading by csv upload
                   3377: #
                   3378: #--- Javascript to handle csv upload
1.27      albertel 3379: sub csvupload_javascript_reverse_associate {
1.246     albertel 3380:     my $error1=&mt('You need to specify the username or ID');
                   3381:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3382:   return(<<ENDPICK);
                   3383:   function verify(vf) {
                   3384:     var foundsomething=0;
                   3385:     var founduname=0;
1.243     albertel 3386:     var foundID=0;
1.27      albertel 3387:     for (i=0;i<=vf.nfields.value;i++) {
                   3388:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3389:       if (i==0 && tw!=0) { foundID=1; }
                   3390:       if (i==1 && tw!=0) { founduname=1; }
                   3391:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3392:     }
1.246     albertel 3393:     if (founduname==0 && foundID==0) {
                   3394: 	alert('$error1');
                   3395: 	return;
1.27      albertel 3396:     }
                   3397:     if (foundsomething==0) {
1.246     albertel 3398: 	alert('$error2');
                   3399: 	return;
1.27      albertel 3400:     }
                   3401:     vf.submit();
                   3402:   }
                   3403:   function flip(vf,tf) {
                   3404:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3405:     var i;
                   3406:     for (i=0;i<=vf.nfields.value;i++) {
                   3407:       //can not pick the same destination field for both name and domain
                   3408:       if (((i ==0)||(i ==1)) && 
                   3409:           ((tf==0)||(tf==1)) && 
                   3410:           (i!=tf) &&
                   3411:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3412:         eval('vf.f'+i+'.selectedIndex=0;')
                   3413:       }
                   3414:     }
                   3415:   }
                   3416: ENDPICK
                   3417: }
                   3418: 
                   3419: sub csvupload_javascript_forward_associate {
1.246     albertel 3420:     my $error1=&mt('You need to specify the username or ID');
                   3421:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3422:   return(<<ENDPICK);
                   3423:   function verify(vf) {
                   3424:     var foundsomething=0;
                   3425:     var founduname=0;
1.243     albertel 3426:     var foundID=0;
1.27      albertel 3427:     for (i=0;i<=vf.nfields.value;i++) {
                   3428:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3429:       if (tw==1) { foundID=1; }
                   3430:       if (tw==2) { founduname=1; }
                   3431:       if (tw>3) { foundsomething=1; }
1.27      albertel 3432:     }
1.246     albertel 3433:     if (founduname==0 && foundID==0) {
                   3434: 	alert('$error1');
                   3435: 	return;
1.27      albertel 3436:     }
                   3437:     if (foundsomething==0) {
1.246     albertel 3438: 	alert('$error2');
                   3439: 	return;
1.27      albertel 3440:     }
                   3441:     vf.submit();
                   3442:   }
                   3443:   function flip(vf,tf) {
                   3444:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3445:     var i;
                   3446:     //can not pick the same destination field twice
                   3447:     for (i=0;i<=vf.nfields.value;i++) {
                   3448:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3449:         eval('vf.f'+i+'.selectedIndex=0;')
                   3450:       }
                   3451:     }
                   3452:   }
                   3453: ENDPICK
                   3454: }
                   3455: 
1.26      albertel 3456: sub csvuploadmap_header {
1.324     albertel 3457:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3458:     my $javascript;
1.257     albertel 3459:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3460: 	$javascript=&csvupload_javascript_reverse_associate();
                   3461:     } else {
                   3462: 	$javascript=&csvupload_javascript_forward_associate();
                   3463:     }
1.45      ng       3464: 
1.324     albertel 3465:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3466:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3467:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3468:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3469:     $request->print(<<ENDPICK);
1.26      albertel 3470: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3471: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3472: $result
1.326     albertel 3473: <hr />
1.26      albertel 3474: <h3>Identify fields</h3>
                   3475: Total number of records found in file: $distotal <hr />
                   3476: Enter as many fields as you can. The system will inform you and bring you back
                   3477: to this page if the data selected is insufficient to run your class.<hr />
                   3478: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3479: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3480: <input type="hidden" name="associate"  value="" />
                   3481: <input type="hidden" name="phase"      value="three" />
                   3482: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3483: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3484: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3485: <input type="hidden" name="upfile_associate" 
1.257     albertel 3486:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3487: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3488: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3489: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3490: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3491: <hr />
                   3492: <script type="text/javascript" language="Javascript">
                   3493: $javascript
                   3494: </script>
                   3495: ENDPICK
1.118     ng       3496:     return '';
1.26      albertel 3497: 
                   3498: }
                   3499: 
                   3500: sub csvupload_fields {
1.324     albertel 3501:     my ($symb) = @_;
                   3502:     my (@parts) = &getpartlist($symb);
1.243     albertel 3503:     my @fields=(['ID','Student ID'],
                   3504: 		['username','Student Username'],
                   3505: 		['domain','Student Domain']);
1.324     albertel 3506:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3507:     foreach my $part (sort(@parts)) {
                   3508: 	my @datum;
                   3509: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3510: 	my $name=$part;
                   3511: 	if  (!$display) { $display = $name; }
                   3512: 	@datum=($name,$display);
1.244     albertel 3513: 	if ($name=~/^stores_(.*)_awarded/) {
                   3514: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3515: 	}
1.41      ng       3516: 	push(@fields,\@datum);
                   3517:     }
                   3518:     return (@fields);
1.26      albertel 3519: }
                   3520: 
                   3521: sub csvuploadmap_footer {
1.41      ng       3522:     my ($request,$i,$keyfields) =@_;
                   3523:     $request->print(<<ENDPICK);
1.26      albertel 3524: </table>
                   3525: <input type="hidden" name="nfields" value="$i" />
                   3526: <input type="hidden" name="keyfields" value="$keyfields" />
                   3527: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3528: </form>
                   3529: ENDPICK
                   3530: }
                   3531: 
1.283     albertel 3532: sub checkforfile_js {
1.86      ng       3533:     my $result =<<CSVFORMJS;
                   3534: <script type="text/javascript" language="javascript">
                   3535:     function checkUpload(formname) {
                   3536: 	if (formname.upfile.value == "") {
                   3537: 	    alert("Please use the browse button to select a file from your local directory.");
                   3538: 	    return false;
                   3539: 	}
                   3540: 	formname.submit();
                   3541:     }
                   3542:     </script>
                   3543: CSVFORMJS
1.283     albertel 3544:     return $result;
                   3545: }
                   3546: 
                   3547: sub upcsvScores_form {
                   3548:     my ($request) = shift;
1.324     albertel 3549:     my ($symb)=&get_symb($request);
1.283     albertel 3550:     if (!$symb) {return '';}
                   3551:     my $result=&checkforfile_js();
1.257     albertel 3552:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3553:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3554:     $result.=$table;
1.326     albertel 3555:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3556:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3557:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3558: 	'.</b></td></tr>'."\n";
                   3559:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3560:     my $upload=&mt("Upload Scores");
1.86      ng       3561:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3562:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3563:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3564:     $result.=<<ENDUPFORM;
1.106     albertel 3565: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3566: <input type="hidden" name="symb" value="$symb" />
                   3567: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3568: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3569: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3570: $upfile_select
1.370     www      3571: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3572: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3573: </form>
                   3574: ENDUPFORM
1.370     www      3575:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3576:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3577:     .'</td></tr></table>'."\n";
1.86      ng       3578:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3579:     $result.=&show_grading_menu_form($symb);
1.86      ng       3580:     return $result;
                   3581: }
                   3582: 
                   3583: 
1.26      albertel 3584: sub csvuploadmap {
1.41      ng       3585:     my ($request)= @_;
1.324     albertel 3586:     my ($symb)=&get_symb($request);
1.41      ng       3587:     if (!$symb) {return '';}
1.72      ng       3588: 
1.41      ng       3589:     my $datatoken;
1.257     albertel 3590:     if (!$env{'form.datatoken'}) {
1.41      ng       3591: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3592:     } else {
1.257     albertel 3593: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3594: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3595:     }
1.41      ng       3596:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3597:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3598:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3599:     my ($i,$keyfields);
                   3600:     if (@records) {
1.324     albertel 3601: 	my @fields=&csvupload_fields($symb);
1.45      ng       3602: 
1.257     albertel 3603: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3604: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3605: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3606: 							  \@fields);
                   3607: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3608: 	    chop($keyfields);
                   3609: 	} else {
                   3610: 	    unshift(@fields,['none','']);
                   3611: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3612: 							    \@fields);
1.311     banghart 3613:             foreach my $rec (@records) {
                   3614:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3615:                 if (%temp) {
                   3616:                     $keyfields=join(',',sort(keys(%temp)));
                   3617:                     last;
                   3618:                 }
                   3619:             }
1.41      ng       3620: 	}
                   3621:     }
                   3622:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3623:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3624: 
1.41      ng       3625:     return '';
1.27      albertel 3626: }
                   3627: 
1.246     albertel 3628: sub csvuploadoptions {
1.41      ng       3629:     my ($request)= @_;
1.324     albertel 3630:     my ($symb)=&get_symb($request);
1.257     albertel 3631:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3632:     my $ignore=&mt('Ignore First Line');
                   3633:     $request->print(<<ENDPICK);
                   3634: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3635: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3636: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3637: <!--
1.246     albertel 3638: <p>
                   3639: <label>
                   3640:    <input type="checkbox" name="show_full_results" />
                   3641:    Show a table of all changes
                   3642: </label>
                   3643: </p>
1.302     albertel 3644: -->
1.246     albertel 3645: <p>
                   3646: <label>
                   3647:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3648:    Overwrite any existing score
                   3649: </label>
                   3650: </p>
                   3651: ENDPICK
                   3652:     my %fields=&get_fields();
                   3653:     if (!defined($fields{'domain'})) {
1.257     albertel 3654: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3655: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3656:     }
1.257     albertel 3657:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3658: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3659: 	my $cleankey=$1;
                   3660: 	if ($cleankey eq 'command') { next; }
                   3661: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3662: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3663:     }
                   3664:     # FIXME do a check for any duplicated user ids...
                   3665:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3666:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3667: <hr /></form>'."\n");
1.324     albertel 3668:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3669:     return '';
                   3670: }
                   3671: 
                   3672: sub get_fields {
                   3673:     my %fields;
1.257     albertel 3674:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3675:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3676: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3677: 	    if ($env{'form.f'.$i} ne 'none') {
                   3678: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3679: 	    }
                   3680: 	} else {
1.257     albertel 3681: 	    if ($env{'form.f'.$i} ne 'none') {
                   3682: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3683: 	    }
                   3684: 	}
1.27      albertel 3685:     }
1.246     albertel 3686:     return %fields;
                   3687: }
                   3688: 
                   3689: sub csvuploadassign {
                   3690:     my ($request)= @_;
1.324     albertel 3691:     my ($symb)=&get_symb($request);
1.246     albertel 3692:     if (!$symb) {return '';}
1.345     bowersj2 3693:     my $error_msg = '';
1.246     albertel 3694:     &Apache::loncommon::load_tmp_file($request);
                   3695:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3696:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3697:     my %fields=&get_fields();
1.41      ng       3698:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3699:     my $courseid=$env{'request.course.id'};
1.97      albertel 3700:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3701:     my @notallowed;
1.41      ng       3702:     my @skipped;
                   3703:     my $countdone=0;
                   3704:     foreach my $grade (@gradedata) {
                   3705: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3706: 	my $domain;
                   3707: 	if ($entries{$fields{'domain'}}) {
                   3708: 	    $domain=$entries{$fields{'domain'}};
                   3709: 	} else {
1.257     albertel 3710: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3711: 	}
1.243     albertel 3712: 	$domain=~s/\s//g;
1.41      ng       3713: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3714: 	$username=~s/\s//g;
1.243     albertel 3715: 	if (!$username) {
                   3716: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3717: 	    $id=~s/\s//g;
1.243     albertel 3718: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3719: 	    $username=$ids{$id};
                   3720: 	}
1.41      ng       3721: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3722: 	    my $id=$entries{$fields{'ID'}};
                   3723: 	    $id=~s/\s//g;
                   3724: 	    if ($id) {
                   3725: 		push(@skipped,"$id:$domain");
                   3726: 	    } else {
                   3727: 		push(@skipped,"$username:$domain");
                   3728: 	    }
1.41      ng       3729: 	    next;
                   3730: 	}
1.108     albertel 3731: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3732: 	if (!&canmodify($usec)) {
                   3733: 	    push(@notallowed,"$username:$domain");
                   3734: 	    next;
                   3735: 	}
1.244     albertel 3736: 	my %points;
1.41      ng       3737: 	my %grades;
                   3738: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3739: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3740: 		$dest eq 'domain') { next; }
                   3741: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3742: 	    if ($dest=~/stores_(.*)_points/) {
                   3743: 		my $part=$1;
                   3744: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3745: 					      $symb,$domain,$username);
1.345     bowersj2 3746:                 if ($wgt) {
                   3747:                     $entries{$fields{$dest}}=~s/\s//g;
                   3748:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3749:                     my $award='correct_by_override';
                   3750:                     $grades{"resource.$part.awarded"}=$pcr;
                   3751:                     $grades{"resource.$part.solved"}=$award;
                   3752:                     $points{$part}=1;
                   3753:                 } else {
                   3754:                     $error_msg = "<br />" .
                   3755:                         &mt("Some point values were assigned"
                   3756:                             ." for problems with a weight "
                   3757:                             ."of zero. These values were "
                   3758:                             ."ignored.");
                   3759:                 }
1.244     albertel 3760: 	    } else {
                   3761: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3762: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3763: 		my $store_key=$dest;
                   3764: 		$store_key=~s/^stores/resource/;
                   3765: 		$store_key=~s/_/\./g;
                   3766: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3767: 	    }
1.41      ng       3768: 	}
1.398     albertel 3769: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3770: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.244     albertel 3771: #	&Apache::lonnet::logthis(" storing ".(join('-',%grades)));
1.302     albertel 3772: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3773: 					   $env{'request.course.id'},
                   3774: 					   $domain,$username);
                   3775: 	if ($result eq 'ok') {
                   3776: 	    $request->print('.');
                   3777: 	} else {
                   3778: 	    $request->print("<p>
1.398     albertel 3779:                               <span class=\"LC_error\">
                   3780:                                  Failed to save student $username:$domain.
                   3781:                                  Message when trying to save was ($result)
                   3782:                               </span>
1.302     albertel 3783:                              </p>" );
                   3784: 	}
1.41      ng       3785: 	$request->rflush();
                   3786: 	$countdone++;
                   3787:     }
1.398     albertel 3788:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3789:     if (@skipped) {
1.398     albertel 3790: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3791: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3792:     }
                   3793:     if (@notallowed) {
1.398     albertel 3794: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3795: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3796:     }
1.106     albertel 3797:     $request->print("<br />\n");
1.324     albertel 3798:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3799:     return $error_msg;
1.26      albertel 3800: }
1.44      ng       3801: #------------- end of section for handling csv file upload ---------
                   3802: #
                   3803: #-------------------------------------------------------------------
                   3804: #
1.122     ng       3805: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3806: #
                   3807: #--- Select a page/sequence and a student to grade
1.68      ng       3808: sub pickStudentPage {
                   3809:     my ($request) = shift;
                   3810: 
                   3811:     $request->print(<<LISTJAVASCRIPT);
                   3812: <script type="text/javascript" language="javascript">
                   3813: 
                   3814: function checkPickOne(formname) {
1.76      ng       3815:     if (radioSelection(formname.student) == null) {
1.68      ng       3816: 	alert("Please select the student you wish to grade.");
                   3817: 	return;
                   3818:     }
1.125     ng       3819:     ptr = pullDownSelection(formname.selectpage);
                   3820:     formname.page.value = formname["page"+ptr].value;
                   3821:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3822:     formname.submit();
                   3823: }
                   3824: 
                   3825: </script>
                   3826: LISTJAVASCRIPT
1.118     ng       3827:     &commonJSfunctions($request);
1.324     albertel 3828:     my ($symb) = &get_symb($request);
1.257     albertel 3829:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3830:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3831:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3832: 
1.398     albertel 3833:     my $result='<h3><span class="LC_info">&nbsp;'.
                   3834: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       3835: 
1.80      ng       3836:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3837:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 3838:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 3839:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3840: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3841: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3842:     my $ctr=0;
1.68      ng       3843:     foreach (@$titles) {
                   3844: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3845: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 3846: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       3847: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3848: 	$ctr++;
1.68      ng       3849:     }
1.326     albertel 3850:     $result.= '</select>'."<br />\n";
1.70      ng       3851:     $ctr=0;
                   3852:     foreach (@$titles) {
                   3853: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3854: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3855: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3856: 	$ctr++;
                   3857:     }
1.72      ng       3858:     $result.='<input type="hidden" name="page" />'."\n".
                   3859: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3860: 
1.401     albertel 3861:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 3862: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       3863: 
1.71      ng       3864:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 3865: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 3866: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 3867: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.72      ng       3868: 
1.68      ng       3869:     $result.='<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
1.257     albertel 3870: 	'<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.72      ng       3871: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 3872: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 3873: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       3874: 
1.382     albertel 3875:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   3876: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   3877: 
1.80      ng       3878:     $result.='&nbsp;<input type="button" '.
1.126     ng       3879: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       3880: 
1.68      ng       3881:     $request->print($result);
                   3882: 
1.326     albertel 3883:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       3884: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3885: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       3886: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3887: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       3888: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3889: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       3890:  
1.76      ng       3891:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       3892:     my $ptr = 1;
1.294     albertel 3893:     foreach my $student (sort 
                   3894: 			 {
                   3895: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3896: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3897: 			     }
                   3898: 			     return $a cmp $b;
                   3899: 			 } (keys(%$fullname))) {
1.68      ng       3900: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       3901: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   3902: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 3903: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   3904: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       3905: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       3906: 	$ptr++;
                   3907:     }
1.381     albertel 3908:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   3909:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       3910:     $studentTable.='<input type="button" '.
                   3911: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       3912: 
1.324     albertel 3913:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       3914:     $request->print($studentTable);
                   3915: 
                   3916:     return '';
                   3917: }
                   3918: 
                   3919: sub getSymbMap {
1.132     bowersj2 3920:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       3921: 
                   3922:     my %symbx = ();
                   3923:     my @titles = ();
1.117     bowersj2 3924:     my $minder = 0;
                   3925: 
                   3926:     # Gather every sequence that has problems.
1.240     albertel 3927:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   3928: 					       1,0,1);
1.117     bowersj2 3929:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 3930: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 3931: 	    my $title = $minder.'.'.
                   3932: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   3933: 	    push(@titles, $title); # minder in case two titles are identical
                   3934: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 3935: 	    $minder++;
1.241     albertel 3936: 	}
1.68      ng       3937:     }
                   3938:     return \@titles,\%symbx;
                   3939: }
                   3940: 
1.72      ng       3941: #
                   3942: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       3943: sub displayPage {
                   3944:     my ($request) = shift;
                   3945: 
1.324     albertel 3946:     my ($symb) = &get_symb($request);
1.257     albertel 3947:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3948:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3949:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3950:     my $pageTitle = $env{'form.page'};
1.103     albertel 3951:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 3952:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   3953:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 3954: 
                   3955:     #need to make sure we have the correct data for later EXT calls, 
                   3956:     #thus invalidate the cache
                   3957:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3958:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3959:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3960:     &Apache::lonnet::clear_EXT_cache_status();
                   3961: 
1.103     albertel 3962:     if (!&canview($usec)) {
1.398     albertel 3963: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 3964: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 3965: 	return;
                   3966:     }
1.398     albertel 3967:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 3968:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       3969: 	'</h3>'."\n";
1.382     albertel 3970:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   3971: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   3972:     } else {
                   3973: 	delete($env{'form.CODE'});
                   3974:     }
1.71      ng       3975:     &sub_page_js($request);
                   3976:     $request->print($result);
                   3977: 
1.132     bowersj2 3978:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 3979:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       3980:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 3981:     if (!$map) {
1.398     albertel 3982: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 3983: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 3984: 	return; 
                   3985:     }
1.68      ng       3986:     my $iterator = $navmap->getIterator($map->map_start(),
                   3987: 					$map->map_finish());
                   3988: 
1.71      ng       3989:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       3990: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 3991: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   3992: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       3993: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 3994: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 3995: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       3996: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 3997: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       3998: 
1.382     albertel 3999:     if (defined($env{'form.CODE'})) {
                   4000: 	$studentTable.=
                   4001: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4002:     }
1.381     albertel 4003:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4004: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4005: 	'/check.gif" height="16" border="0" />';
                   4006: 
1.118     ng       4007:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4008: 	' symbol.'."\n".
1.71      ng       4009: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4010: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4011: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4012: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4013: 
1.329     albertel 4014:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4015:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4016:     $iterator->next(); # skip the first BEGIN_MAP
                   4017:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4018:     while ($depth > 0) {
1.68      ng       4019:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4020:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4021: 
1.385     albertel 4022:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4023: 	    my $parts = $curRes->parts();
1.68      ng       4024:             my $title = $curRes->compTitle();
1.71      ng       4025: 	    my $symbx = $curRes->symb();
1.196     albertel 4026: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4027: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4028: 	    $studentTable.='<td valign="top">';
1.382     albertel 4029: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4030: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4031: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4032: 					     undef,'both',\%form);
1.71      ng       4033: 	    } else {
1.382     albertel 4034: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4035: 		$companswer =~ s|<form(.*?)>||g;
                   4036: 		$companswer =~ s|</form>||g;
1.71      ng       4037: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4038: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4039: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4040: #		}
1.116     ng       4041: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4042: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4043: 	    }
                   4044: 
1.257     albertel 4045: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4046: 
1.257     albertel 4047: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4048: 		if ($record{'version'} eq '') {
1.398     albertel 4049: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4050: 		} else {
1.116     ng       4051: 		    my %responseType = ();
                   4052: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4053: 			my @responseIds =$curRes->responseIds($partid);
                   4054: 			my @responseType =$curRes->responseType($partid);
                   4055: 			my %responseIds;
                   4056: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4057: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4058: 			}
                   4059: 			$responseType{$partid} = \%responseIds;
1.116     ng       4060: 		    }
1.148     albertel 4061: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4062: 
1.71      ng       4063: 		}
1.257     albertel 4064: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4065: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4066: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4067: 									$env{'request.course.id'},
1.71      ng       4068: 									'','.submission');
                   4069:  
                   4070: 	    }
1.103     albertel 4071: 	    if (&canmodify($usec)) {
                   4072: 		foreach my $partid (@{$parts}) {
                   4073: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4074: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4075: 		    $question++;
                   4076: 		}
1.196     albertel 4077: 		$prob++;
1.71      ng       4078: 	    }
                   4079: 	    $studentTable.='</td></tr>';
1.68      ng       4080: 
1.103     albertel 4081: 	}
1.68      ng       4082:         $curRes = $iterator->next();
                   4083:     }
                   4084: 
1.381     albertel 4085:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4086: 	'<input type="button" value="Save" '.
1.381     albertel 4087: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4088: 	'</form>'."\n";
1.324     albertel 4089:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4090:     $request->print($studentTable);
                   4091: 
                   4092:     return '';
1.119     ng       4093: }
                   4094: 
                   4095: sub displaySubByDates {
1.148     albertel 4096:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4097:     my $isCODE=0;
1.335     albertel 4098:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4099:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4100:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4101: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4102: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4103: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4104: 	'<td><b>Submission</b></td>'.
                   4105: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4106:     my ($version);
                   4107:     my %mark;
1.148     albertel 4108:     my %orders;
1.119     ng       4109:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4110:     if (!exists($$record{'1:timestamp'})) {
1.398     albertel 4111: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
1.147     albertel 4112:     }
1.335     albertel 4113: 
                   4114:     my $interaction;
1.119     ng       4115:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4116: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4117: 	if (exists($$record{$version.':resource.0.version'})) {
                   4118: 	    $interaction = $$record{$version.':resource.0.version'};
                   4119: 	}
                   4120: 
                   4121: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4122: 		             : "$version:resource");
                   4123: 	#&Apache::lonnet::logthis(" got $where");
1.119     ng       4124: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4125: 	if ($isCODE) {
                   4126: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4127: 	}
1.119     ng       4128: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4129: 	my @displaySub = ();
                   4130: 	foreach my $partid (@{$parts}) {
1.335     albertel 4131: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4132: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4133: 	    
                   4134: 
1.122     ng       4135: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4136: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4137: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4138: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4139: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4140: 
                   4141: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4142: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   4143: 		    #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
1.207     albertel 4144: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.398     albertel 4145: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
                   4146: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4147: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4148: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4149: 		    } else {
                   4150: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4151: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4152: 		    }
1.335     albertel 4153: 		    my $responseType=($isTask ? 'Task'
                   4154:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4155: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4156: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4157: 			$orders{$partid}->{$responseId}=
                   4158: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4159: 		    }
1.147     albertel 4160: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4161: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4162: 		}
                   4163: 	    }
1.335     albertel 4164: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4165: 		$displaySub[1].='Checked in by '.
                   4166: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4167: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4168: 		    '<br />';
                   4169: 	    }
                   4170: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4171: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4172: 		    lc($$record{"$where.$partid.award"}).' '.
                   4173: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4174: 		    '<br />';
                   4175: 	    }
1.335     albertel 4176: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4177: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4178: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4179: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4180: 		$displaySub[2].=
                   4181: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4182: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4183: 	    }
                   4184: 	}
                   4185: 	# needed because old essay regrader has not parts info
                   4186: 	if (exists $$record{"$version:resource.regrader"}) {
                   4187: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4188: 	}
                   4189: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4190: 	if ($displaySub[2]) {
                   4191: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4192: 	}
1.382     albertel 4193: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4194:     
1.119     ng       4195:     }
                   4196:     $studentTable.='</table></td></tr></table>';
                   4197:     return $studentTable;
1.71      ng       4198: }
                   4199: 
                   4200: sub updateGradeByPage {
                   4201:     my ($request) = shift;
                   4202: 
1.257     albertel 4203:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4204:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4205:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4206:     my $pageTitle = $env{'form.page'};
1.103     albertel 4207:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4208:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4209:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4210:     if (!&canmodify($usec)) {
1.398     albertel 4211: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4212: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4213: 	return;
                   4214:     }
1.398     albertel 4215:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4216:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4217: 	'</h3>'."\n";
1.70      ng       4218: 
1.68      ng       4219:     $request->print($result);
                   4220: 
1.132     bowersj2 4221:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4222:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4223:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4224:     if (!$map) {
1.398     albertel 4225: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4226: 	my ($symb)=&get_symb($request);
                   4227: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4228: 	return; 
                   4229:     }
1.71      ng       4230:     my $iterator = $navmap->getIterator($map->map_start(),
                   4231: 					$map->map_finish());
1.70      ng       4232: 
1.71      ng       4233:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4234: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4235: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4236: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4237: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4238: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4239: 
                   4240:     $iterator->next(); # skip the first BEGIN_MAP
                   4241:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4242:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4243:     while ($depth > 0) {
1.71      ng       4244:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4245:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4246: 
1.385     albertel 4247:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4248: 	    my $parts = $curRes->parts();
1.71      ng       4249:             my $title = $curRes->compTitle();
                   4250: 	    my $symbx = $curRes->symb();
1.196     albertel 4251: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4252: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4253: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4254: 
                   4255: 	    my %newrecord=();
                   4256: 	    my @displayPts=();
1.269     raeburn  4257:             my %aggregate = ();
                   4258:             my $aggregateflag = 0;
1.71      ng       4259: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4260: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4261: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4262: 
1.257     albertel 4263: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4264: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4265: 		my $partial = $newpts/$wgt;
                   4266: 		my $score;
                   4267: 		if ($partial > 0) {
                   4268: 		    $score = 'correct_by_override';
1.125     ng       4269: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4270: 		    $score = 'incorrect_by_override';
                   4271: 		}
1.257     albertel 4272: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4273: 		if ($dropMenu eq 'excused') {
1.71      ng       4274: 		    $partial = '';
                   4275: 		    $score = 'excused';
1.125     ng       4276: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4277: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4278: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4279: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4280: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4281: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4282: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4283: 		    $changeflag++;
                   4284: 		    $newpts = '';
1.269     raeburn  4285:                     
                   4286:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4287:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4288:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4289:                     if ($aggtries > 0) {
                   4290:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4291:                         $aggregateflag = 1;
                   4292:                     }
1.71      ng       4293: 		}
1.324     albertel 4294: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4295: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4296: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4297: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4298: 		    '&nbsp;<br />';
1.207     albertel 4299: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4300: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4301: 		    '&nbsp;<br />';
1.71      ng       4302: 		$question++;
1.380     albertel 4303: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4304: 
1.71      ng       4305: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4306: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4307: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4308: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4309: 
                   4310: 		$changeflag++;
                   4311: 	    }
                   4312: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4313: 		my %record = 
                   4314: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4315: 					     $udom,$uname);
                   4316: 
                   4317: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4318: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4319: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4320: 		    $newrecord{'resource.CODE'} = '';
                   4321: 		}
1.257     albertel 4322: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4323: 					$udom,$uname);
1.382     albertel 4324: 		%record = &Apache::lonnet::restore($symbx,
                   4325: 						   $env{'request.course.id'},
                   4326: 						   $udom,$uname);
1.380     albertel 4327: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4328: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4329: 	    }
1.380     albertel 4330: 	    
1.269     raeburn  4331:             if ($aggregateflag) {
                   4332:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4333:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4334:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4335:             }
1.125     ng       4336: 
1.71      ng       4337: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4338: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4339: 		'</tr>';
1.68      ng       4340: 
1.196     albertel 4341: 	    $prob++;
1.68      ng       4342: 	}
1.71      ng       4343:         $curRes = $iterator->next();
1.68      ng       4344:     }
1.98      albertel 4345: 
1.71      ng       4346:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4347:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4348:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4349: 		  'The scores were changed for '.
                   4350: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4351:     $request->print($grademsg.$studentTable);
1.68      ng       4352: 
1.70      ng       4353:     return '';
                   4354: }
                   4355: 
1.72      ng       4356: #-------- end of section for handling grading by page/sequence ---------
                   4357: #
                   4358: #-------------------------------------------------------------------
                   4359: 
1.75      albertel 4360: #--------------------Scantron Grading-----------------------------------
                   4361: #
                   4362: #------ start of section for handling grading by page/sequence ---------
                   4363: 
1.423     albertel 4364: =pod
                   4365: 
                   4366: =head1 Bubble sheet grading routines
                   4367: 
1.424     albertel 4368:   For this documentation:
                   4369: 
                   4370:    'scanline' refers to the full line of characters
                   4371:    from the file that we are parsing that represents one entire sheet
                   4372: 
                   4373:    'bubble line' refers to the data
                   4374:    representing the line of bubbles that are on the physical bubble sheet
                   4375: 
                   4376: 
                   4377: The overall process is that a scanned in bubble sheet data is uploaded
                   4378: into a course. When a user wants to grade, they select a
                   4379: sequence/folder of resources, a file of bubble sheet info, and pick
                   4380: one of the predefined configurations for what each scanline looks
                   4381: like.
                   4382: 
                   4383: Next each scanline is checked for any errors of either 'missing
                   4384: bubbles' (it's an error because it may have been missed scanned
                   4385: because too light bubbling), 'double bubble' (each bubble line should
                   4386: have no more that one letter picked), invalid or duplicated CODE,
                   4387: invalid student ID
                   4388: 
                   4389: If the CODE option is used that determines the randomization of the
                   4390: homework problems, either way the student ID is looked up into a
                   4391: username:domain.
                   4392: 
                   4393: During the validation phase the instructor can choose to skip scanlines. 
                   4394: 
                   4395: After the validation phase, there is now 3 bubble sheet files
                   4396: 
                   4397:   scantron_original_filename (unmodified original file)
                   4398:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4399:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4400: 
                   4401: Also there is a separate hash nohist_scantrondata that contains extra
                   4402: correction information that isn't representable in the bubble sheet
                   4403: file (see &scantron_getfile() for more information)
                   4404: 
                   4405: After all scanlines are either valid, marked as valid or skipped, then
                   4406: foreach line foreach problem in the picked sequence, an ssi request is
                   4407: made that simulates a user submitting their selected letter(s) against
                   4408: the homework problem.
1.423     albertel 4409: 
                   4410: =over 4
                   4411: 
                   4412: =cut
                   4413: 
                   4414: 
                   4415: =pod 
                   4416: 
                   4417: =item defaultFormData
                   4418: 
                   4419:   Returns html hidden inputs used to hold context/default values.
                   4420: 
                   4421:  Arguments:
                   4422:   $symb - $symb of the current resource 
                   4423: 
                   4424: =cut
1.422     foxr     4425: 
1.81      albertel 4426: sub defaultFormData {
1.324     albertel 4427:     my ($symb)=@_;
1.81      albertel 4428:     return '
1.418     albertel 4429:       <input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4430:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4431:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4432: }
                   4433: 
1.423     albertel 4434: =pod 
                   4435: 
                   4436: =item getSequenceDropDown
                   4437: 
                   4438:    Return html dropdown of possible sequences to grade
                   4439:  
                   4440:  Arguments:
                   4441:    $symb - $symb of the current resource 
                   4442: 
                   4443: =cut
1.422     foxr     4444: 
1.75      albertel 4445: sub getSequenceDropDown {
1.423     albertel 4446:     my ($symb)=@_;
1.75      albertel 4447:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4448:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4449:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4450:     my $ctr=0;
                   4451:     foreach (@$titles) {
                   4452: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4453: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4454: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4455: 	    '>'.$showtitle.'</option>'."\n";
                   4456: 	$ctr++;
                   4457:     }
                   4458:     $result.= '</select>';
                   4459:     return $result;
                   4460: }
                   4461: 
1.423     albertel 4462: 
                   4463: =pod 
                   4464: 
                   4465: =item scantron_filenames
                   4466: 
                   4467:    Returns a list of the scantron files in the current course 
                   4468: 
                   4469: =cut
1.422     foxr     4470: 
1.202     albertel 4471: sub scantron_filenames {
1.257     albertel 4472:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4473:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4474:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4475: 				    &propath($cdom,$cname));
1.202     albertel 4476:     my @possiblenames;
1.201     albertel 4477:     foreach my $filename (sort(@files)) {
1.157     albertel 4478: 	($filename)=split(/&/,$filename);
                   4479: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4480: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4481: 	push(@possiblenames,$filename);
                   4482:     }
                   4483:     return @possiblenames;
                   4484: }
                   4485: 
1.423     albertel 4486: =pod 
                   4487: 
                   4488: =item scantron_uploads
                   4489: 
                   4490:    Returns  html drop-down list of scantron files in current course.
                   4491: 
                   4492:  Arguments:
                   4493:    $file2grade - filename to set as selected in the dropdown
                   4494: 
                   4495: =cut
1.422     foxr     4496: 
1.202     albertel 4497: sub scantron_uploads {
1.209     ng       4498:     my ($file2grade) = @_;
1.202     albertel 4499:     my $result=	'<select name="scantron_selectfile">';
                   4500:     $result.="<option></option>";
                   4501:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4502: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4503:     }
                   4504:     $result.="</select>";
                   4505:     return $result;
                   4506: }
                   4507: 
1.423     albertel 4508: =pod 
                   4509: 
                   4510: =item scantron_scantab
                   4511: 
                   4512:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4513:   file.
                   4514: 
                   4515: =cut
1.422     foxr     4516: 
1.82      albertel 4517: sub scantron_scantab {
                   4518:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4519:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4520:     $result.='<option></option>'."\n";
1.82      albertel 4521:     foreach my $line (<$fh>) {
                   4522: 	my ($name,$descrip)=split(/:/,$line);
                   4523: 	if ($name =~ /^\#/) { next; }
                   4524: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4525:     }
                   4526:     $result.='</select>'."\n";
                   4527: 
                   4528:     return $result;
                   4529: }
                   4530: 
1.423     albertel 4531: =pod 
                   4532: 
                   4533: =item scantron_CODElist
                   4534: 
                   4535:   Returns html drop down of the saved CODE lists from current course,
                   4536:   generated from earlier printings.
                   4537: 
                   4538: =cut
1.422     foxr     4539: 
1.186     albertel 4540: sub scantron_CODElist {
1.257     albertel 4541:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4542:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4543:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4544:     my $namechoice='<option></option>';
1.225     albertel 4545:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4546: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4547: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4548: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4549:     }
                   4550:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4551:     return $namechoice;
                   4552: }
                   4553: 
1.423     albertel 4554: =pod 
                   4555: 
                   4556: =item scantron_CODEunique
                   4557: 
                   4558:   Returns the html for "Each CODE to be used once" radio.
                   4559: 
                   4560: =cut
1.422     foxr     4561: 
1.186     albertel 4562: sub scantron_CODEunique {
1.381     albertel 4563:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4564:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4565:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4566:                 </span>
                   4567:                 <span style="white-space: nowrap;">
1.272     albertel 4568:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4569:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4570:                 </span>';
1.186     albertel 4571:     return $result;
                   4572: }
1.423     albertel 4573: 
                   4574: =pod 
                   4575: 
                   4576: =item scantron_selectphase
                   4577: 
                   4578:   Generates the initial screen to start the bubble sheet process.
                   4579:   Allows for - starting a grading run.
1.424     albertel 4580:              - downloading existing scan data (original, corrected
1.423     albertel 4581:                                                 or skipped info)
                   4582: 
                   4583:              - uploading new scan data
                   4584: 
                   4585:  Arguments:
                   4586:   $r          - The Apache request object
                   4587:   $file2grade - name of the file that contain the scanned data to score
                   4588: 
                   4589: =cut
1.186     albertel 4590: 
1.75      albertel 4591: sub scantron_selectphase {
1.209     ng       4592:     my ($r,$file2grade) = @_;
1.324     albertel 4593:     my ($symb)=&get_symb($r);
1.75      albertel 4594:     if (!$symb) {return '';}
1.423     albertel 4595:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4596:     my $default_form_data=&defaultFormData($symb);
                   4597:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4598:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4599:     my $format_selector=&scantron_scantab();
1.186     albertel 4600:     my $CODE_selector=&scantron_CODElist();
                   4601:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4602:     my $result;
1.422     foxr     4603: 
                   4604:     # Chunk of form to prompt for a file to grade and how:
                   4605: 
1.75      albertel 4606:     $result.= <<SCANTRONFORM;
1.162     albertel 4607:     <table width="100%" border="0">
1.75      albertel 4608:     <tr>
1.226     albertel 4609:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4610:       <td bgcolor="#777777">
1.203     albertel 4611:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4612:         $default_form_data
1.75      albertel 4613:         <table width="100%" border="0">
                   4614:           <tr bgcolor="#e6ffff">
1.174     albertel 4615:             <td colspan="2">
                   4616:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4617:             </td>
                   4618:           </tr>
                   4619:           <tr bgcolor="#ffffe6">
1.174     albertel 4620:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4621:           </tr>
                   4622:           <tr bgcolor="#ffffe6">
1.174     albertel 4623:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4624:           </tr>
1.82      albertel 4625:           <tr bgcolor="#ffffe6">
1.174     albertel 4626:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4627:           </tr>
1.157     albertel 4628:           <tr bgcolor="#ffffe6">
1.186     albertel 4629:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4630:           </tr>
                   4631:           <tr bgcolor="#ffffe6">
                   4632:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4633:           </tr>
                   4634:           <tr bgcolor="#ffffe6">
1.187     albertel 4635: 	    <td> Options: </td>
                   4636:             <td>
1.272     albertel 4637: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4638:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4639:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4640: 	    </td>
                   4641:           </tr>
                   4642:           <tr bgcolor="#ffffe6">
1.174     albertel 4643:             <td colspan="2">
1.265     www      4644:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4645:             </td>
                   4646:           </tr>
                   4647:         </table>
1.226     albertel 4648:        </td>
                   4649:      </form>
1.162     albertel 4650:     </tr>
                   4651: SCANTRONFORM
                   4652:    
                   4653:     $r->print($result);
                   4654: 
1.257     albertel 4655:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4656:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4657: 
1.422     foxr     4658: 	# Chunk of form to prompt for a scantron file upload.
                   4659: 
1.162     albertel 4660:         $r->print(<<SCANTRONFORM);
                   4661:     <tr>
                   4662:       <td bgcolor="#777777">
                   4663:         <table width="100%" border="0">
                   4664:           <tr bgcolor="#e6ffff">
                   4665:             <td>
1.174     albertel 4666:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4667:             </td>
                   4668:           </tr>
                   4669:           <tr bgcolor="#ffffe6">
                   4670:             <td>
                   4671: SCANTRONFORM
1.324     albertel 4672:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4673:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4674:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4675:     $r->print(<<UPLOAD);
                   4676:               <script type="text/javascript" language="javascript">
                   4677:     function checkUpload(formname) {
                   4678: 	if (formname.upfile.value == "") {
                   4679: 	    alert("Please use the browse button to select a file from your local directory.");
                   4680: 	    return false;
                   4681: 	}
                   4682: 	formname.submit();
                   4683:     }
                   4684:               </script>
                   4685: 
                   4686:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4687:                 $default_form_data
                   4688:                 <input name='courseid' type='hidden' value='$cnum' />
                   4689:                 <input name='domainid' type='hidden' value='$cdom' />
                   4690:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4691:                 File to upload:<input type="file" name="upfile" size="50" />
                   4692:                 <br />
                   4693:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4694:               </form>
                   4695: UPLOAD
1.162     albertel 4696: 
                   4697:         $r->print(<<SCANTRONFORM);
                   4698:             </td>
                   4699:           </tr>
1.75      albertel 4700:         </table>
                   4701:       </td>
                   4702:     </tr>
1.162     albertel 4703: SCANTRONFORM
                   4704:     }
1.422     foxr     4705: 
                   4706:     # Chunk of the form that prompts to view a scoring office file,
                   4707:     # corrected file, skipped records in a file.
                   4708: 
1.187     albertel 4709:     $r->print(<<SCANTRONFORM);
                   4710:     <tr>
1.226     albertel 4711:       <form action='/adm/grades' name='scantron_download'>
                   4712:         <td bgcolor="#777777">
1.379     albertel 4713: 	  $default_form_data
1.187     albertel 4714:           <input type="hidden" name="command" value="scantron_download" />
                   4715:           <table width="100%" border="0">
                   4716:             <tr bgcolor="#e6ffff">
                   4717:               <td colspan="2">
                   4718:                 &nbsp;<b>Download a scoring office file</b>
                   4719:               </td>
                   4720:             </tr>
                   4721:             <tr bgcolor="#ffffe6">
                   4722:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4723:             </tr>
                   4724:             <tr bgcolor="#ffffe6">
                   4725:               <td colspan="2">
1.293     www      4726:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4727:               </td>
                   4728:             </tr>
                   4729:           </table>
1.226     albertel 4730:         </td>
                   4731:       </form>
1.187     albertel 4732:     </tr>
                   4733: SCANTRONFORM
1.162     albertel 4734: 
                   4735:     $r->print(<<SCANTRONFORM);
1.75      albertel 4736:   </table>
1.81      albertel 4737: $grading_menu_button
1.75      albertel 4738: SCANTRONFORM
                   4739: 
1.162     albertel 4740:     return
1.75      albertel 4741: }
                   4742: 
1.423     albertel 4743: =pod
                   4744: 
                   4745: =item get_scantron_config
                   4746: 
                   4747:    Parse and return the scantron configuration line selected as a
                   4748:    hash of configuration file fields.
                   4749: 
                   4750:  Arguments:
                   4751:     which - the name of the configuration to parse from the file.
                   4752: 
                   4753: 
                   4754:  Returns:
                   4755:             If the named configuration is not in the file, an empty
                   4756:             hash is returned.
                   4757:     a hash with the fields
                   4758:       name         - internal name for the this configuration setup
                   4759:       description  - text to display to operator that describes this config
                   4760:       CODElocation - if 0 or the string 'none'
                   4761:                           - no CODE exists for this config
                   4762:                      if -1 || the string 'letter'
                   4763:                           - a CODE exists for this config and is
                   4764:                             a string of letters
                   4765:                      Unsupported value (but planned for future support)
                   4766:                           if a positive integer
                   4767:                                - The CODE exists as the first n items from
                   4768:                                  the question section of the form
                   4769:                           if the string 'number'
                   4770:                                - The CODE exists for this config and is
                   4771:                                  a string of numbers
                   4772:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4773:                      the CODE starts
                   4774:       CODElength  - length of the CODE
                   4775:       IDstart     - column where the student ID number starts
                   4776:       IDlength    - length of the student ID info
                   4777:       Qstart      - column where the information from the bubbled
                   4778:                     'questions' start
                   4779:       Qlength     - number of columns comprising a single bubble line from
                   4780:                     the sheet. (usually either 1 or 10)
1.424     albertel 4781:       Qon         - either a single character representing the character used
1.423     albertel 4782:                     to signal a bubble was chosen in the positional setup, or
                   4783:                     the string 'letter' if the letter of the chosen bubble is
                   4784:                     in the final, or 'number' if a number representing the
                   4785:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 4786:       Qoff        - the character used to represent that a bubble was
                   4787:                     left blank
1.423     albertel 4788:       PaperID     - if the scanning process generates a unique number for each
                   4789:                     sheet scanned the column that this ID number starts in
                   4790:       PaperIDlength - number of columns that comprise the unique ID number
                   4791:                       for the sheet of paper
1.424     albertel 4792:       FirstName   - column that the first name starts in
1.423     albertel 4793:       FirstNameLength - number of columns that the first name spans
                   4794:  
                   4795:       LastName    - column that the last name starts in
                   4796:       LastNameLength - number of columns that the last name spans
                   4797: 
                   4798: =cut
1.422     foxr     4799: 
1.82      albertel 4800: sub get_scantron_config {
                   4801:     my ($which) = @_;
                   4802:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4803:     my %config;
1.157     albertel 4804:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4805:     foreach my $line (<$fh>) {
                   4806: 	my ($name,$descrip)=split(/:/,$line);
                   4807: 	if ($name ne $which ) { next; }
                   4808: 	chomp($line);
                   4809: 	my @config=split(/:/,$line);
                   4810: 	$config{'name'}=$config[0];
                   4811: 	$config{'description'}=$config[1];
                   4812: 	$config{'CODElocation'}=$config[2];
                   4813: 	$config{'CODEstart'}=$config[3];
                   4814: 	$config{'CODElength'}=$config[4];
                   4815: 	$config{'IDstart'}=$config[5];
                   4816: 	$config{'IDlength'}=$config[6];
                   4817: 	$config{'Qstart'}=$config[7];
                   4818: 	$config{'Qlength'}=$config[8];
                   4819: 	$config{'Qoff'}=$config[9];
                   4820: 	$config{'Qon'}=$config[10];
1.157     albertel 4821: 	$config{'PaperID'}=$config[11];
                   4822: 	$config{'PaperIDlength'}=$config[12];
                   4823: 	$config{'FirstName'}=$config[13];
                   4824: 	$config{'FirstNamelength'}=$config[14];
                   4825: 	$config{'LastName'}=$config[15];
                   4826: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4827: 	last;
                   4828:     }
                   4829:     return %config;
                   4830: }
                   4831: 
1.423     albertel 4832: =pod 
                   4833: 
                   4834: =item username_to_idmap
                   4835: 
                   4836:     creates a hash keyed by student id with values of the corresponding
                   4837:     student username:domain.
                   4838: 
                   4839:   Arguments:
                   4840: 
                   4841:     $classlist - reference to the class list hash. This is a hash
                   4842:                  keyed by student name:domain  whose elements are references
1.424     albertel 4843:                  to arrays containing various chunks of information
1.423     albertel 4844:                  about the student. (See loncoursedata for more info).
                   4845: 
                   4846:   Returns
                   4847:     %idmap - the constructed hash
                   4848: 
                   4849: =cut
                   4850: 
1.82      albertel 4851: sub username_to_idmap {
                   4852:     my ($classlist)= @_;
                   4853:     my %idmap;
                   4854:     foreach my $student (keys(%$classlist)) {
                   4855: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4856: 	    $student;
                   4857:     }
                   4858:     return %idmap;
                   4859: }
1.423     albertel 4860: 
                   4861: =pod
                   4862: 
1.424     albertel 4863: =item scantron_fixup_scanline
1.423     albertel 4864: 
                   4865:    Process a requested correction to a scanline.
                   4866: 
                   4867:   Arguments:
                   4868:     $scantron_config   - hash from &get_scantron_config()
                   4869:     $scan_data         - hash of correction information 
                   4870:                           (see &scantron_getfile())
                   4871:     $line              - existing scanline
                   4872:     $whichline         - line number of the passed in scanline
                   4873:     $field             - type of change to process 
                   4874:                          (either 
                   4875:                           'ID'     -> correct the student ID number
                   4876:                           'CODE'   -> correct the CODE
                   4877:                           'answer' -> fixup the submitted answers)
                   4878:     
                   4879:    $args               - hash of additional info,
                   4880:                           - 'ID' 
                   4881:                                'newid' -> studentID to use in replacement
1.424     albertel 4882:                                           of existing one
1.423     albertel 4883:                           - 'CODE' 
                   4884:                                'CODE_ignore_dup' - set to true if duplicates
                   4885:                                                    should be ignored.
                   4886: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 4887:                                         if the existing unfound code should
1.423     albertel 4888:                                         be used as is
                   4889:                           - 'answer'
                   4890:                                'response' - new answer or 'none' if blank
                   4891:                                'question' - the bubble line to change
                   4892: 
                   4893:   Returns:
                   4894:     $line - the modified scanline
                   4895: 
                   4896:   Side effects: 
                   4897:     $scan_data - may be updated
                   4898: 
                   4899: =cut
                   4900: 
1.82      albertel 4901: 
1.157     albertel 4902: sub scantron_fixup_scanline {
                   4903:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.423     albertel 4904: 
1.157     albertel 4905:     if ($field eq 'ID') {
                   4906: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 4907: 	    return ($line,1,'New value too large');
1.157     albertel 4908: 	}
                   4909: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   4910: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   4911: 				     $args->{'newid'});
                   4912: 	}
                   4913: 	substr($line,$$scantron_config{'IDstart'}-1,
                   4914: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   4915: 	if ($args->{'newid'}=~/^\s*$/) {
                   4916: 	    &scan_data($scan_data,"$whichline.user",
                   4917: 		       $args->{'username'}.':'.$args->{'domain'});
                   4918: 	}
1.186     albertel 4919:     } elsif ($field eq 'CODE') {
1.192     albertel 4920: 	if ($args->{'CODE_ignore_dup'}) {
                   4921: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   4922: 	}
                   4923: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   4924: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 4925: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   4926: 		return ($line,1,'New CODE value too large');
                   4927: 	    }
                   4928: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   4929: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   4930: 	    }
                   4931: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   4932: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 4933: 	}
1.157     albertel 4934:     } elsif ($field eq 'answer') {
                   4935: 	my $length=$scantron_config->{'Qlength'};
                   4936: 	my $off=$scantron_config->{'Qoff'};
                   4937: 	my $on=$scantron_config->{'Qon'};
                   4938: 	my $answer=${off}x$length;
                   4939: 	if ($args->{'response'} eq 'none') {
                   4940: 	    &scan_data($scan_data,
                   4941: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   4942: 	} else {
1.274     albertel 4943: 	    if ($on eq 'letter') {
                   4944: 		my @alphabet=('A'..'Z');
                   4945: 		$answer=$alphabet[$args->{'response'}];
                   4946: 	    } elsif ($on eq 'number') {
                   4947: 		$answer=$args->{'response'}+1;
1.389     albertel 4948: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 4949: 	    } else {
                   4950: 		substr($answer,$args->{'response'},1)=$on;
                   4951: 	    }
1.157     albertel 4952: 	    &scan_data($scan_data,
                   4953: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   4954: 	}
                   4955: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   4956: 	substr($line,$where-1,$length)=$answer;
                   4957:     }
                   4958:     return $line;
                   4959: }
1.423     albertel 4960: 
                   4961: =pod
                   4962: 
                   4963: =item scan_data
                   4964: 
                   4965:     Edit or look up  an item in the scan_data hash.
                   4966: 
                   4967:   Arguments:
                   4968:     $scan_data  - The hash (see scantron_getfile)
                   4969:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 4970:                   scantronfilename_key).
1.423     albertel 4971:     $data        - New value of the hash entry.
                   4972:     $delete      - If true, the entry is removed from the hash.
                   4973: 
                   4974:   Returns:
                   4975:     The new value of the hash table field (undefined if deleted).
                   4976: 
                   4977: =cut
                   4978: 
                   4979: 
1.157     albertel 4980: sub scan_data {
                   4981:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 4982:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 4983:     if (defined($value)) {
                   4984: 	$scan_data->{$filename.'_'.$key} = $value;
                   4985:     }
                   4986:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   4987:     return $scan_data->{$filename.'_'.$key};
                   4988: }
1.423     albertel 4989: 
                   4990: =pod 
                   4991: 
                   4992: =item scantron_parse_scanline
                   4993: 
                   4994:   Decodes a scanline from the selected scantron file
                   4995: 
                   4996:  Arguments:
                   4997:     line             - The text of the scantron file line to process
                   4998:     whichline        - Line number
                   4999:     scantron_config  - Hash describing the format of the scantron lines.
                   5000:     scan_data        - Hash of extra information about the scanline
                   5001:                        (see scantron_getfile for more information)
                   5002:     just_header      - True if should not process question answers but only
                   5003:                        the stuff to the left of the answers.
                   5004:  Returns:
                   5005:    Hash containing the result of parsing the scanline
                   5006: 
                   5007:    Keys are all proceeded by the string 'scantron.'
                   5008: 
                   5009:        CODE    - the CODE in use for this scanline
                   5010:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5011:                  by the operator
                   5012:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5013:                             CODEs were selected, but the usage has been
                   5014:                             forced by the operator
                   5015:        ID  - student ID
                   5016:        PaperID - if used, the ID number printed on the sheet when the 
                   5017:                  paper was scanned
                   5018:        FirstName - first name from the sheet
                   5019:        LastName  - last name from the sheet
                   5020: 
                   5021:      if just_header was not true these key may also exist
                   5022: 
                   5023:        missingerror - a list of bubbled line numbers that had a blank bubble
                   5024:                       that is considered an error (if the operator had already
                   5025:                       okayed a blank bubble line as really being blank then
                   5026:                       that bubble line number won't appear here.
                   5027:        doubleerror  - a list of bubbled line numbers that had more than one
                   5028:                       bubble filled in and has not been corrected by the
                   5029:                       operator
                   5030:        maxquest     - the number of the last bubble line that was parsed
                   5031: 
                   5032:        (<number> starts at 1)
                   5033:        <number>.answer - zero or more letters representing the selected
                   5034:                          letters from the scanline for the bubble line 
                   5035:                          <number>.
                   5036:                          if blank there was either no bubble or there where
                   5037:                          multiple bubbles, (consult the keys missingerror and
                   5038:                          doubleerror if this is an error condition)
                   5039: 
                   5040: =cut
                   5041: 
1.82      albertel 5042: sub scantron_parse_scanline {
1.423     albertel 5043:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.82      albertel 5044:     my %record;
1.422     foxr     5045:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5046:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5047:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5048: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5049: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5050: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5051: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5052: 	    $record{'scantron.CODE'}=substr($data,
                   5053: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5054: 					    $$scantron_config{'CODElength'});
1.191     albertel 5055: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5056: 		$record{'scantron.useCODE'}=1;
                   5057: 	    }
1.192     albertel 5058: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5059: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5060: 	    }
1.82      albertel 5061: 	} else {
                   5062: 	    #FIXME interpret first N questions
                   5063: 	}
                   5064:     }
1.83      albertel 5065:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5066: 				  $$scantron_config{'IDlength'});
1.157     albertel 5067:     $record{'scantron.PaperID'}=
                   5068: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5069: 	       $$scantron_config{'PaperIDlength'});
                   5070:     $record{'scantron.FirstName'}=
                   5071: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5072: 	       $$scantron_config{'FirstNamelength'});
                   5073:     $record{'scantron.LastName'}=
                   5074: 	substr($data,$$scantron_config{'LastName'}-1,
                   5075: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5076:     if ($just_header) { return \%record; }
1.194     albertel 5077: 
1.82      albertel 5078:     my @alphabet=('A'..'Z');
                   5079:     my $questnum=0;
                   5080:     while ($questions) {
                   5081: 	$questnum++;
                   5082: 	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
                   5083: 	substr($questions,0,$$scantron_config{'Qlength'})='';
1.83      albertel 5084: 	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
1.239     albertel 5085: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.371     albertel 5086: 	    if ($currentquest eq '?'
                   5087: 		|| $currentquest eq '*') {
1.274     albertel 5088: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5089: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 5090: 	    } elsif (!defined($currentquest)
1.274     albertel 5091: 		     || $currentquest eq $$scantron_config{'Qoff'}
                   5092: 		     || $currentquest !~ /^[A-Z]$/) {
1.239     albertel 5093: 		$record{"scantron.$questnum.answer"}='';
                   5094: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5095: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5096: 		}
                   5097: 	    } else {
                   5098: 		$record{"scantron.$questnum.answer"}=$currentquest;
                   5099: 	    }
                   5100: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.371     albertel 5101: 	    if ($currentquest eq '?'
                   5102: 		|| $currentquest eq '*') {
1.274     albertel 5103: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5104: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 5105: 	    } elsif (!defined($currentquest)
                   5106: 		     || $currentquest eq $$scantron_config{'Qoff'} 
                   5107: 		     || $currentquest !~ /^\d$/) {
1.239     albertel 5108: 		$record{"scantron.$questnum.answer"}='';
                   5109: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5110: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5111: 		}
                   5112: 	    } else {
1.371     albertel 5113: 		# wrap zero back to J
                   5114: 		if ($currentquest eq '0') {
                   5115: 		    $record{"scantron.$questnum.answer"}=
                   5116: 			$alphabet[9];
                   5117: 		} else {
                   5118: 		    $record{"scantron.$questnum.answer"}=
                   5119: 			$alphabet[$currentquest-1];
                   5120: 		}
1.239     albertel 5121: 	    }
1.82      albertel 5122: 	} else {
1.239     albertel 5123: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
                   5124: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}) {
                   5125: 		$record{"scantron.$questnum.answer"}='';
                   5126: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5127: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5128: 		}
                   5129: 	    } else {
                   5130: 		$record{"scantron.$questnum.answer"}=
                   5131: 		    $alphabet[length($array[0])];
                   5132: 	    }
                   5133: 	    if (scalar(@array) gt 2) {
                   5134: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5135: 		my @ans=@array;
                   5136: 		my $i=length($ans[0]);shift(@ans);
                   5137: 		while ($#ans) {
                   5138: 		    $i+=length($ans[0])+1;
                   5139: 		    $record{"scantron.$questnum.answer"}.=$alphabet[$i];
                   5140: 		    shift(@ans);
                   5141: 		}
                   5142: 	    }
1.82      albertel 5143: 	}
                   5144:     }
1.83      albertel 5145:     $record{'scantron.maxquest'}=$questnum;
                   5146:     return \%record;
1.82      albertel 5147: }
                   5148: 
1.423     albertel 5149: =pod
                   5150: 
                   5151: =item scantron_add_delay
                   5152: 
                   5153:    Adds an error message that occurred during the grading phase to a
                   5154:    queue of messages to be shown after grading pass is complete
                   5155: 
                   5156:  Arguments:
1.424     albertel 5157:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5158:    $scanline    - the scanline that caused the error
                   5159:    $errormesage - the error message
                   5160:    $errorcode   - a numeric code for the error
                   5161: 
                   5162:  Side Effects:
1.424     albertel 5163:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5164: 
                   5165: =cut
                   5166: 
1.82      albertel 5167: sub scantron_add_delay {
1.140     albertel 5168:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5169:     push(@$delayqueue,
                   5170: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5171: 	  'ecode' => $errorcode }
                   5172: 	 );
1.82      albertel 5173: }
                   5174: 
1.423     albertel 5175: =pod
                   5176: 
                   5177: =item scantron_find_student
                   5178: 
1.424     albertel 5179:    Finds the username for the current scanline
                   5180: 
                   5181:   Arguments:
                   5182:    $scantron_record - hash result from scantron_parse_scanline
                   5183:    $scan_data       - hash of correction information 
                   5184:                       (see &scantron_getfile() form more information)
                   5185:    $idmap           - hash from &username_to_idmap()
                   5186:    $line            - number of current scanline
                   5187:  
                   5188:   Returns:
                   5189:    Either 'username:domain' or undef if unknown
                   5190: 
1.423     albertel 5191: =cut
                   5192: 
1.82      albertel 5193: sub scantron_find_student {
1.157     albertel 5194:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5195:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5196:     if ($scanID =~ /^\s*$/) {
                   5197:  	return &scan_data($scan_data,"$line.user");
                   5198:     }
1.83      albertel 5199:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5200:  	if (lc($id) eq lc($scanID)) {
                   5201:  	    return $$idmap{$id};
                   5202:  	}
1.83      albertel 5203:     }
                   5204:     return undef;
                   5205: }
                   5206: 
1.423     albertel 5207: =pod
                   5208: 
                   5209: =item scantron_filter
                   5210: 
1.424     albertel 5211:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5212:    hidden resources was selected
                   5213: 
1.423     albertel 5214: =cut
                   5215: 
1.83      albertel 5216: sub scantron_filter {
                   5217:     my ($curres)=@_;
1.331     albertel 5218: 
                   5219:     if (ref($curres) && $curres->is_problem()) {
                   5220: 	# if the user has asked to not have either hidden
                   5221: 	# or 'randomout' controlled resources to be graded
                   5222: 	# don't include them
                   5223: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5224: 	    && $curres->randomout) {
                   5225: 	    return 0;
                   5226: 	}
1.83      albertel 5227: 	return 1;
                   5228:     }
                   5229:     return 0;
1.82      albertel 5230: }
                   5231: 
1.423     albertel 5232: =pod
                   5233: 
                   5234: =item scantron_process_corrections
                   5235: 
1.424     albertel 5236:    Gets correction information out of submitted form data and corrects
                   5237:    the scanline
                   5238: 
1.423     albertel 5239: =cut
                   5240: 
1.157     albertel 5241: sub scantron_process_corrections {
                   5242:     my ($r) = @_;
1.257     albertel 5243:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5244:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5245:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5246:     my $which=$env{'form.scantron_line'};
1.200     albertel 5247:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5248:     my ($skip,$err,$errmsg);
1.257     albertel 5249:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5250: 	$skip=1;
1.257     albertel 5251:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5252: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5253: 	    $env{'form.scantron_domain'};
1.157     albertel 5254: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5255: 	($line,$err,$errmsg)=
                   5256: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5257: 				     'ID',{'newid'=>$newid,
1.257     albertel 5258: 				    'username'=>$env{'form.scantron_username'},
                   5259: 				    'domain'=>$env{'form.scantron_domain'}});
                   5260:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5261: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5262: 	my $newCODE;
1.192     albertel 5263: 	my %args;
1.190     albertel 5264: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5265: 	    $newCODE='use_unfound';
1.190     albertel 5266: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5267: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5268: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5269: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5270: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5271: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5272: 	}
1.257     albertel 5273: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5274: 	    $args{'CODE_ignore_dup'}=1;
                   5275: 	}
                   5276: 	$args{'CODE'}=$newCODE;
1.186     albertel 5277: 	($line,$err,$errmsg)=
                   5278: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5279: 				     'CODE',\%args);
1.257     albertel 5280:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5281: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5282: 	    ($line,$err,$errmsg)=
                   5283: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5284: 					 $which,'answer',
                   5285: 					 { 'question'=>$question,
1.257     albertel 5286: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5287: 	    if ($err) { last; }
                   5288: 	}
                   5289:     }
                   5290:     if ($err) {
1.398     albertel 5291: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5292:     } else {
1.200     albertel 5293: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5294: 	&scantron_putfile($scanlines,$scan_data);
                   5295:     }
                   5296: }
                   5297: 
1.423     albertel 5298: =pod
                   5299: 
                   5300: =item reset_skipping_status
                   5301: 
1.424     albertel 5302:    Forgets the current set of remember skipped scanlines (and thus
                   5303:    reverts back to considering all lines in the
                   5304:    scantron_skipped_<filename> file)
                   5305: 
1.423     albertel 5306: =cut
                   5307: 
1.200     albertel 5308: sub reset_skipping_status {
                   5309:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5310:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5311:     &scantron_putfile(undef,$scan_data);
                   5312: }
                   5313: 
1.423     albertel 5314: =pod
                   5315: 
                   5316: =item start_skipping
                   5317: 
1.424     albertel 5318:    Marks a scanline to be skipped. 
                   5319: 
1.423     albertel 5320: =cut
                   5321: 
1.376     albertel 5322: sub start_skipping {
1.200     albertel 5323:     my ($scan_data,$i)=@_;
                   5324:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5325:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5326: 	$remembered{$i}=2;
                   5327:     } else {
                   5328: 	$remembered{$i}=1;
                   5329:     }
1.200     albertel 5330:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5331: }
                   5332: 
1.423     albertel 5333: =pod
                   5334: 
                   5335: =item should_be_skipped
                   5336: 
1.424     albertel 5337:    Checks whether a scanline should be skipped.
                   5338: 
1.423     albertel 5339: =cut
                   5340: 
1.200     albertel 5341: sub should_be_skipped {
1.376     albertel 5342:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5343:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5344: 	# not redoing old skips
1.376     albertel 5345: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5346: 	return 0;
                   5347:     }
                   5348:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5349: 
                   5350:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5351: 	return 0;
                   5352:     }
1.200     albertel 5353:     return 1;
                   5354: }
                   5355: 
1.423     albertel 5356: =pod
                   5357: 
                   5358: =item remember_current_skipped
                   5359: 
1.424     albertel 5360:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5361:    file and remembers them into scan_data for later use.
                   5362: 
1.423     albertel 5363: =cut
                   5364: 
1.200     albertel 5365: sub remember_current_skipped {
                   5366:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5367:     my %to_remember;
                   5368:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5369: 	if ($scanlines->{'skipped'}[$i]) {
                   5370: 	    $to_remember{$i}=1;
                   5371: 	}
                   5372:     }
1.376     albertel 5373: 
1.200     albertel 5374:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5375:     &scantron_putfile(undef,$scan_data);
                   5376: }
                   5377: 
1.423     albertel 5378: =pod
                   5379: 
                   5380: =item check_for_error
                   5381: 
1.424     albertel 5382:     Checks if there was an error when attempting to remove a specific
                   5383:     scantron_.. bubble sheet data file. Prints out an error if
                   5384:     something went wrong.
                   5385: 
1.423     albertel 5386: =cut
                   5387: 
1.200     albertel 5388: sub check_for_error {
                   5389:     my ($r,$result)=@_;
                   5390:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5391: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5392:     }
                   5393: }
1.157     albertel 5394: 
1.423     albertel 5395: =pod
                   5396: 
                   5397: =item scantron_warning_screen
                   5398: 
1.424     albertel 5399:    Interstitial screen to make sure the operator has selected the
                   5400:    correct options before we start the validation phase.
                   5401: 
1.423     albertel 5402: =cut
                   5403: 
1.203     albertel 5404: sub scantron_warning_screen {
                   5405:     my ($button_text)=@_;
1.257     albertel 5406:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5407:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5408:     my $CODElist;
1.284     albertel 5409:     if ($scantron_config{'CODElocation'} &&
                   5410: 	$scantron_config{'CODEstart'} &&
                   5411: 	$scantron_config{'CODElength'}) {
                   5412: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5413: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5414: 	$CODElist=
                   5415: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5416: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5417:     }
1.203     albertel 5418:     return (<<STUFF);
                   5419: <p>
1.398     albertel 5420: <span class="LC_warning">Please double check the information
                   5421:                  below before clicking on '$button_text'</span>
1.203     albertel 5422: </p>
                   5423: <table>
1.284     albertel 5424: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5425: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5426: $CODElist
1.203     albertel 5427: </table>
                   5428: <br />
                   5429: <p> If this information is correct, please click on '$button_text'.</p>
                   5430: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5431: 
                   5432: <br />
                   5433: STUFF
                   5434: }
                   5435: 
1.423     albertel 5436: =pod
                   5437: 
                   5438: =item scantron_do_warning
                   5439: 
1.424     albertel 5440:    Check if the operator has picked something for all required
                   5441:    fields. Error out if something is missing.
                   5442: 
1.423     albertel 5443: =cut
                   5444: 
1.203     albertel 5445: sub scantron_do_warning {
                   5446:     my ($r)=@_;
1.324     albertel 5447:     my ($symb)=&get_symb($r);
1.203     albertel 5448:     if (!$symb) {return '';}
1.324     albertel 5449:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5450:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5451:     if ( $env{'form.selectpage'} eq '' ||
                   5452: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5453: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5454: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5455: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5456: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5457: 	} 
1.257     albertel 5458: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5459: 	    $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 5460: 	} 
1.257     albertel 5461: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5462: 	    $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 5463: 	} 
                   5464:     } else {
1.265     www      5465: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5466: 	$r->print(<<STUFF);
1.203     albertel 5467: $warning
1.265     www      5468: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5469: <input type="hidden" name="command" value="scantron_validate" />
                   5470: STUFF
1.237     albertel 5471:     }
1.352     albertel 5472:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5473:     return '';
                   5474: }
                   5475: 
1.423     albertel 5476: =pod
                   5477: 
                   5478: =item scantron_form_start
                   5479: 
1.424     albertel 5480:     html hidden input for remembering all selected grading options
                   5481: 
1.423     albertel 5482: =cut
                   5483: 
1.203     albertel 5484: sub scantron_form_start {
                   5485:     my ($max_bubble)=@_;
                   5486:     my $result= <<SCANTRONFORM;
                   5487: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5488:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5489:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5490:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5491:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5492:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5493:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5494:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5495:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5496:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5497: SCANTRONFORM
                   5498:     return $result;
                   5499: }
                   5500: 
1.423     albertel 5501: =pod
                   5502: 
                   5503: =item scantron_validate_file
                   5504: 
1.424     albertel 5505:     Dispatch routine for doing validation of a bubble sheet data file.
                   5506: 
                   5507:     Also processes any necessary information resets that need to
                   5508:     occur before validation begins (ignore previous corrections,
                   5509:     restarting the skipped records processing)
                   5510: 
1.423     albertel 5511: =cut
                   5512: 
1.157     albertel 5513: sub scantron_validate_file {
                   5514:     my ($r) = @_;
1.324     albertel 5515:     my ($symb)=&get_symb($r);
1.157     albertel 5516:     if (!$symb) {return '';}
1.324     albertel 5517:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5518:     
                   5519:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5520:     # them when doing the corrections reset
1.257     albertel 5521:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5522: 	&reset_skipping_status();
                   5523:     }
1.257     albertel 5524:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5525: 	&remember_current_skipped();
1.257     albertel 5526: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5527:     }
                   5528: 
1.257     albertel 5529:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5530: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5531: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5532: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5533: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5534:     }
1.200     albertel 5535: 
1.257     albertel 5536:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5537: 	&scantron_process_corrections($r);
                   5538:     }
1.424     albertel 5539:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5540:     #get the student pick code ready
                   5541:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5542:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5543:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5544:     $r->print($result);
                   5545:     
1.334     albertel 5546:     my @validate_phases=( 'sequence',
                   5547: 			  'ID',
1.157     albertel 5548: 			  'CODE',
                   5549: 			  'doublebubble',
                   5550: 			  'missingbubbles');
1.257     albertel 5551:     if (!$env{'form.validatepass'}) {
                   5552: 	$env{'form.validatepass'} = 0;
1.157     albertel 5553:     }
1.257     albertel 5554:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5555: 
                   5556:     my $stop=0;
                   5557:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5558: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5559: 	$r->rflush();
                   5560: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5561: 	{
                   5562: 	    no strict 'refs';
                   5563: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5564: 	}
                   5565:     }
                   5566:     if (!$stop) {
1.203     albertel 5567: 	my $warning=&scantron_warning_screen('Start Grading');
                   5568: 	$r->print(<<STUFF);
                   5569: Validation process complete.<br />
                   5570: $warning
                   5571: <input type="submit" name="submit" value="Start Grading" />
                   5572: <input type="hidden" name="command" value="scantron_process" />
                   5573: STUFF
                   5574: 
1.157     albertel 5575:     } else {
                   5576: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5577: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5578:     }
                   5579:     if ($stop) {
1.334     albertel 5580: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5581: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5582: 	    $r->print(' this error <br />');
                   5583: 
                   5584: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5585: 	} else {
                   5586: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5587: 	    $r->print(' using corrected info <br />');
                   5588: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5589: 	    $r->print(" this scanline saving it for later.");
                   5590: 	}
1.157     albertel 5591:     }
1.352     albertel 5592:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5593:     return '';
                   5594: }
                   5595: 
1.423     albertel 5596: 
                   5597: =pod
                   5598: 
                   5599: =item scantron_remove_file
                   5600: 
1.424     albertel 5601:    Removes the requested bubble sheet data file, makes sure that
                   5602:    scantron_original_<filename> is never removed
                   5603: 
                   5604: 
1.423     albertel 5605: =cut
                   5606: 
1.200     albertel 5607: sub scantron_remove_file {
1.192     albertel 5608:     my ($which)=@_;
1.257     albertel 5609:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5610:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5611:     my $file='scantron_';
1.200     albertel 5612:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5613: 	$file.=$which.'_';
1.192     albertel 5614:     } else {
                   5615: 	return 'refused';
                   5616:     }
1.257     albertel 5617:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5618:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5619: }
                   5620: 
1.423     albertel 5621: 
                   5622: =pod
                   5623: 
                   5624: =item scantron_remove_scan_data
                   5625: 
1.424     albertel 5626:    Removes all scan_data correction for the requested bubble sheet
                   5627:    data file.  (In the case that both the are doing skipped records we need
                   5628:    to remember the old skipped lines for the time being so that element
                   5629:    persists for a while.)
                   5630: 
1.423     albertel 5631: =cut
                   5632: 
1.200     albertel 5633: sub scantron_remove_scan_data {
1.257     albertel 5634:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5635:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5636:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5637:     my @todelete;
1.257     albertel 5638:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5639:     foreach my $key (@keys) {
                   5640: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5641: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5642: 		$key=~/remember_skipping/) {
                   5643: 		next;
                   5644: 	    }
1.192     albertel 5645: 	    push(@todelete,$key);
                   5646: 	}
                   5647:     }
1.200     albertel 5648:     my $result;
1.192     albertel 5649:     if (@todelete) {
1.200     albertel 5650: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5651:     }
                   5652:     return $result;
                   5653: }
                   5654: 
1.423     albertel 5655: 
                   5656: =pod
                   5657: 
                   5658: =item scantron_getfile
                   5659: 
1.424     albertel 5660:     Fetches the requested bubble sheet data file (all 3 versions), and
                   5661:     the scan_data hash
                   5662:   
                   5663:   Arguments:
                   5664:     None
                   5665: 
                   5666:   Returns:
                   5667:     2 hash references
                   5668: 
                   5669:      - first one has 
                   5670:          orig      -
                   5671:          corrected -
                   5672:          skipped   -  each of which points to an array ref of the specified
                   5673:                       file broken up into individual lines
                   5674:          count     - number of scanlines
                   5675:  
                   5676:      - second is the scan_data hash possible keys are
1.425     albertel 5677:        ($number refers to scanline numbered $number and thus the key affects
                   5678:         only that scanline
                   5679:         $bubline refers to the specific bubble line element and the aspects
                   5680:         refers to that specific bubble line element)
                   5681: 
                   5682:        $number.user - username:domain to use
                   5683:        $number.CODE_ignore_dup 
                   5684:                     - ignore the duplicate CODE error 
                   5685:        $number.useCODE
                   5686:                     - use the CODE in the scanline as is
                   5687:        $number.no_bubble.$bubline
                   5688:                     - it is valid that there is no bubbled in bubble
                   5689:                       at $number $bubline
                   5690:        remember_skipping
                   5691:                     - a frozen hash containing keys of $number and values
                   5692:                       of either 
                   5693:                         1 - we are on a 'do skipped records pass' and plan
                   5694:                             on processing this line
                   5695:                         2 - we are on a 'do skipped records pass' and this
                   5696:                             scanline has been marked to skip yet again
1.424     albertel 5697: 
1.423     albertel 5698: =cut
                   5699: 
1.157     albertel 5700: sub scantron_getfile {
1.200     albertel 5701:     #FIXME really would prefer a scantron directory
1.257     albertel 5702:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5703:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5704:     my $lines;
                   5705:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5706: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5707:     my %scanlines;
                   5708:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5709:     my $temp=$scanlines{'orig'};
                   5710:     $scanlines{'count'}=$#$temp;
                   5711: 
                   5712:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5713: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5714:     if ($lines eq '-1') {
                   5715: 	$scanlines{'corrected'}=[];
                   5716:     } else {
                   5717: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5718:     }
                   5719:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5720: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5721:     if ($lines eq '-1') {
                   5722: 	$scanlines{'skipped'}=[];
                   5723:     } else {
                   5724: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5725:     }
1.175     albertel 5726:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5727:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5728:     my %scan_data = @tmp;
                   5729:     return (\%scanlines,\%scan_data);
                   5730: }
                   5731: 
1.423     albertel 5732: =pod
                   5733: 
                   5734: =item lonnet_putfile
                   5735: 
1.424     albertel 5736:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   5737: 
                   5738:  Arguments:
                   5739:    $contents - data to store
                   5740:    $filename - filename to store $contents into
                   5741: 
                   5742:  Returns:
                   5743:    result value from &Apache::lonnet::finishuserfileupload
                   5744: 
1.423     albertel 5745: =cut
                   5746: 
1.157     albertel 5747: sub lonnet_putfile {
                   5748:     my ($contents,$filename)=@_;
1.257     albertel 5749:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5750:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5751:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 5752:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 5753: 
                   5754: }
                   5755: 
1.423     albertel 5756: =pod
                   5757: 
                   5758: =item scantron_putfile
                   5759: 
1.424     albertel 5760:     Stores the current version of the bubble sheet data files, and the
                   5761:     scan_data hash. (Does not modify the original version only the
                   5762:     corrected and skipped versions.
                   5763: 
                   5764:  Arguments:
                   5765:     $scanlines - hash ref that looks like the first return value from
                   5766:                  &scantron_getfile()
                   5767:     $scan_data - hash ref that looks like the second return value from
                   5768:                  &scantron_getfile()
                   5769: 
1.423     albertel 5770: =cut
                   5771: 
1.157     albertel 5772: sub scantron_putfile {
                   5773:     my ($scanlines,$scan_data) = @_;
1.200     albertel 5774:     #FIXME really would prefer a scantron directory
1.257     albertel 5775:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5776:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 5777:     if ($scanlines) {
                   5778: 	my $prefix='scantron_';
1.157     albertel 5779: # no need to update orig, shouldn't change
                   5780: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 5781: #		    $env{'form.scantron_selectfile'});
1.200     albertel 5782: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   5783: 			$prefix.'corrected_'.
1.257     albertel 5784: 			$env{'form.scantron_selectfile'});
1.200     albertel 5785: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   5786: 			$prefix.'skipped_'.
1.257     albertel 5787: 			$env{'form.scantron_selectfile'});
1.200     albertel 5788:     }
1.175     albertel 5789:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 5790: }
                   5791: 
1.423     albertel 5792: =pod
                   5793: 
                   5794: =item scantron_get_line
                   5795: 
1.424     albertel 5796:    Returns the correct version of the scanline
                   5797: 
                   5798:  Arguments:
                   5799:     $scanlines - hash ref that looks like the first return value from
                   5800:                  &scantron_getfile()
                   5801:     $scan_data - hash ref that looks like the second return value from
                   5802:                  &scantron_getfile()
                   5803:     $i         - number of the requested line (starts at 0)
                   5804: 
                   5805:  Returns:
                   5806:    A scanline, (either the original or the corrected one if it
                   5807:    exists), or undef if the requested scanline should be
                   5808:    skipped. (Either because it's an skipped scanline, or it's an
                   5809:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   5810:    pass.
                   5811: 
1.423     albertel 5812: =cut
                   5813: 
1.157     albertel 5814: sub scantron_get_line {
1.200     albertel 5815:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 5816:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   5817:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 5818:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   5819:     return $scanlines->{'orig'}[$i]; 
                   5820: }
                   5821: 
1.423     albertel 5822: =pod
                   5823: 
                   5824: =item scantron_todo_count
                   5825: 
1.424     albertel 5826:     Counts the number of scanlines that need processing.
                   5827: 
                   5828:  Arguments:
                   5829:     $scanlines - hash ref that looks like the first return value from
                   5830:                  &scantron_getfile()
                   5831:     $scan_data - hash ref that looks like the second return value from
                   5832:                  &scantron_getfile()
                   5833: 
                   5834:  Returns:
                   5835:     $count - number of scanlines to process
                   5836: 
1.423     albertel 5837: =cut
                   5838: 
1.200     albertel 5839: sub get_todo_count {
                   5840:     my ($scanlines,$scan_data)=@_;
                   5841:     my $count=0;
                   5842:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5843: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   5844: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5845: 	$count++;
                   5846:     }
                   5847:     return $count;
                   5848: }
                   5849: 
1.423     albertel 5850: =pod
                   5851: 
                   5852: =item scantron_put_line
                   5853: 
1.424     albertel 5854:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   5855:     data file.
                   5856: 
                   5857:  Arguments:
                   5858:     $scanlines - hash ref that looks like the first return value from
                   5859:                  &scantron_getfile()
                   5860:     $scan_data - hash ref that looks like the second return value from
                   5861:                  &scantron_getfile()
                   5862:     $i         - line number to update
                   5863:     $newline   - contents of the updated scanline
                   5864:     $skip      - if true make the line for skipping and update the
                   5865:                  'skipped' file
                   5866: 
1.423     albertel 5867: =cut
                   5868: 
1.157     albertel 5869: sub scantron_put_line {
1.200     albertel 5870:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 5871:     if ($skip) {
                   5872: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 5873: 	&start_skipping($scan_data,$i);
1.157     albertel 5874: 	return;
                   5875:     }
                   5876:     $scanlines->{'corrected'}[$i]=$newline;
                   5877: }
                   5878: 
1.423     albertel 5879: =pod
                   5880: 
                   5881: =item scantron_clear_skip
                   5882: 
1.424     albertel 5883:    Remove a line from the 'skipped' file
                   5884: 
                   5885:  Arguments:
                   5886:     $scanlines - hash ref that looks like the first return value from
                   5887:                  &scantron_getfile()
                   5888:     $scan_data - hash ref that looks like the second return value from
                   5889:                  &scantron_getfile()
                   5890:     $i         - line number to update
                   5891: 
1.423     albertel 5892: =cut
                   5893: 
1.376     albertel 5894: sub scantron_clear_skip {
                   5895:     my ($scanlines,$scan_data,$i)=@_;
                   5896:     if (exists($scanlines->{'skipped'}[$i])) {
                   5897: 	undef($scanlines->{'skipped'}[$i]);
                   5898: 	return 1;
                   5899:     }
                   5900:     return 0;
                   5901: }
                   5902: 
1.423     albertel 5903: =pod
                   5904: 
                   5905: =item scantron_filter_not_exam
                   5906: 
1.424     albertel 5907:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   5908:    filter out resources that are not marked as 'exam' mode
                   5909: 
1.423     albertel 5910: =cut
                   5911: 
1.334     albertel 5912: sub scantron_filter_not_exam {
                   5913:     my ($curres)=@_;
                   5914:     
                   5915:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   5916: 	# if the user has asked to not have either hidden
                   5917: 	# or 'randomout' controlled resources to be graded
                   5918: 	# don't include them
                   5919: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5920: 	    && $curres->randomout) {
                   5921: 	    return 0;
                   5922: 	}
                   5923: 	return 1;
                   5924:     }
                   5925:     return 0;
                   5926: }
                   5927: 
1.423     albertel 5928: =pod
                   5929: 
                   5930: =item scantron_validate_sequence
                   5931: 
1.424     albertel 5932:     Validates the selected sequence, checking for resource that are
                   5933:     not set to exam mode.
                   5934: 
1.423     albertel 5935: =cut
                   5936: 
1.334     albertel 5937: sub scantron_validate_sequence {
                   5938:     my ($r,$currentphase) = @_;
                   5939: 
                   5940:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5941:     my (undef,undef,$sequence)=
                   5942: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   5943: 
                   5944:     my $map=$navmap->getResourceByUrl($sequence);
                   5945: 
                   5946:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   5947:                                     value="ignore" />');
                   5948:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   5949: 	my @resources=
                   5950: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   5951: 	if (@resources) {
1.357     banghart 5952: 	    $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 5953: 	    return (1,$currentphase);
                   5954: 	}
                   5955:     }
                   5956: 
                   5957:     return (0,$currentphase+1);
                   5958: }
                   5959: 
1.423     albertel 5960: =pod
                   5961: 
                   5962: =item scantron_validate_ID
                   5963: 
1.424     albertel 5964:    Validates all scanlines in the selected file to not have any
                   5965:    invalid or underspecified student IDs
                   5966: 
1.423     albertel 5967: =cut
                   5968: 
1.157     albertel 5969: sub scantron_validate_ID {
                   5970:     my ($r,$currentphase) = @_;
                   5971:     
                   5972:     #get student info
                   5973:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5974:     my %idmap=&username_to_idmap($classlist);
                   5975: 
                   5976:     #get scantron line setup
1.257     albertel 5977:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5978:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5979: 
                   5980:     my %found=('ids'=>{},'usernames'=>{});
                   5981:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5982: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5983: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5984: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5985: 						 $scan_data);
                   5986: 	my $id=$$scan_record{'scantron.ID'};
                   5987: 	my $found;
                   5988: 	foreach my $checkid (keys(%idmap)) {
                   5989: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   5990: 	}
                   5991: 	if ($found) {
                   5992: 	    my $username=$idmap{$found};
                   5993: 	    if ($found{'ids'}{$found}) {
                   5994: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5995: 					 $line,'duplicateID',$found);
1.194     albertel 5996: 		return(1,$currentphase);
1.157     albertel 5997: 	    } elsif ($found{'usernames'}{$username}) {
                   5998: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5999: 					 $line,'duplicateID',$username);
1.194     albertel 6000: 		return(1,$currentphase);
1.157     albertel 6001: 	    }
1.186     albertel 6002: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6003: 	    $found{'ids'}{$found}++;
                   6004: 	    $found{'usernames'}{$username}++;
                   6005: 	} else {
                   6006: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6007: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6008: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6009: 		    &scantron_get_correction($r,$i,$scan_record,
                   6010: 					     \%scantron_config,
                   6011: 					     $line,'duplicateID',$username);
1.194     albertel 6012: 		    return(1,$currentphase);
1.157     albertel 6013: 		} elsif (!defined($username)) {
                   6014: 		    &scantron_get_correction($r,$i,$scan_record,
                   6015: 					     \%scantron_config,
                   6016: 					     $line,'incorrectID');
1.194     albertel 6017: 		    return(1,$currentphase);
1.157     albertel 6018: 		}
                   6019: 		$found{'usernames'}{$username}++;
                   6020: 	    } else {
                   6021: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6022: 					 $line,'incorrectID');
1.194     albertel 6023: 		return(1,$currentphase);
1.157     albertel 6024: 	    }
                   6025: 	}
                   6026:     }
                   6027: 
                   6028:     return (0,$currentphase+1);
                   6029: }
                   6030: 
1.423     albertel 6031: =pod
                   6032: 
                   6033: =item scantron_get_correction
                   6034: 
1.424     albertel 6035:    Builds the interface screen to interact with the operator to fix a
                   6036:    specific error condition in a specific scanline
                   6037: 
                   6038:  Arguments:
                   6039:     $r           - Apache request object
                   6040:     $i           - number of the current scanline
                   6041:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6042:     $scan_config - hash ref as returned from &get_scantron_config()
                   6043:     $line        - full contents of the current scanline
                   6044:     $error       - error condition, valid values are
                   6045:                    'incorrectCODE', 'duplicateCODE',
                   6046:                    'doublebubble', 'missingbubble',
                   6047:                    'duplicateID', 'incorrectID'
                   6048:     $arg         - extra information needed
                   6049:        For errors:
                   6050:          - duplicateID   - paper number that this studentID was seen before on
                   6051:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6052:                            seen on before
                   6053:          - incorrectCODE - current incorrect CODE 
                   6054:          - doublebubble  - array ref of the bubble lines that have double
                   6055:                            bubble errors
                   6056:          - missingbubble - array ref of the bubble lines that have missing
                   6057:                            bubble errors
                   6058: 
1.423     albertel 6059: =cut
                   6060: 
1.157     albertel 6061: sub scantron_get_correction {
                   6062:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6063: 
                   6064: #FIXME in the case of a duplicated ID the previous line, probaly need
                   6065: #to show both the current line and the previous one and allow skipping
                   6066: #the previous one or the current one
                   6067: 
1.161     albertel 6068:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6069:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6070: 	$r->print(" for PaperID <tt>".
                   6071: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6072:     } else {
                   6073: 	$r->print(" in scanline $i <pre>".
                   6074: 		  $line."</pre> \n");
                   6075:     }
1.242     albertel 6076:     my $message="<p>The ID on the form is  <tt>".
                   6077: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6078: 	"The name on the paper is ".
                   6079: 	$$scan_record{'scantron.LastName'}.",".
                   6080: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6081: 
1.157     albertel 6082:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6083:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6084:     if ($error =~ /ID$/) {
1.186     albertel 6085: 	if ($error eq 'incorrectID') {
1.157     albertel 6086: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6087: 	} elsif ($error eq 'duplicateID') {
                   6088: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6089: 	}
1.242     albertel 6090: 	$r->print($message);
1.157     albertel 6091: 	$r->print("<p>How should I handle this? <br /> \n");
                   6092: 	$r->print("\n<ul><li> ");
                   6093: 	#FIXME it would be nice if this sent back the user ID and
                   6094: 	#could do partial userID matches
                   6095: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6096: 				       'scantron_username','scantron_domain'));
                   6097: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6098: 	$r->print("\n@".
1.257     albertel 6099: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6100: 
                   6101: 	$r->print('</li>');
1.186     albertel 6102:     } elsif ($error =~ /CODE$/) {
                   6103: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6104: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6105: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6106: 	    $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 6107: 	}
1.224     albertel 6108: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6109: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6110: 	$r->print($message);
1.186     albertel 6111: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6112: 	$r->print("\n<br /> ");
1.194     albertel 6113: 	my $i=0;
1.273     albertel 6114: 	if ($error eq 'incorrectCODE' 
                   6115: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6116: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6117: 	    if ($closest > 0) {
                   6118: 		foreach my $testcode (@{$closest}) {
                   6119: 		    my $checked='';
1.401     albertel 6120: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6121: 		    $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' />");
                   6122: 		    $r->print("\n<br />");
                   6123: 		    $i++;
                   6124: 		}
1.194     albertel 6125: 	    }
                   6126: 	}
1.273     albertel 6127: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6128: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6129: 	    $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>");
                   6130: 	    $r->print("\n<br />");
                   6131: 	}
1.194     albertel 6132: 
1.188     albertel 6133: 	$r->print(<<ENDSCRIPT);
                   6134: <script type="text/javascript">
                   6135: function change_radio(field) {
1.190     albertel 6136:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6137:     var i;
                   6138:     for (i=0;i<slct.length;i++) {
                   6139:         if (slct[i].value==field) { slct[i].checked=true; }
                   6140:     }
                   6141: }
                   6142: </script>
                   6143: ENDSCRIPT
1.187     albertel 6144: 	my $href="/adm/pickcode?".
1.359     www      6145: 	   "form=".&escape("scantronupload").
                   6146: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6147: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6148: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6149: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6150: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6151: 	    $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')\" />");
                   6152: 	    $r->print("\n<br />");
                   6153: 	}
1.272     albertel 6154: 	$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 6155: 	$r->print("\n<br /><br />");
1.157     albertel 6156:     } elsif ($error eq 'doublebubble') {
                   6157: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6158: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6159: 		  join(',',@{$arg}).'" />');
1.242     albertel 6160: 	$r->print($message);
1.157     albertel 6161: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6162: 	foreach my $question (@{$arg}) {
                   6163: 	    my $selected=$$scan_record{"scantron.$question.answer"};
1.422     foxr     6164: 	    &scantron_bubble_selector($r,$scan_config,$question,
                   6165: 				      split('',$selected));
1.157     albertel 6166: 	}
                   6167:     } elsif ($error eq 'missingbubble') {
                   6168: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6169: 	$r->print($message);
1.157     albertel 6170: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6171: 	$r->print("Some questions have no scanned bubbles\n");
                   6172: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6173: 		  join(',',@{$arg}).'" />');
                   6174: 	foreach my $question (@{$arg}) {
                   6175: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   6176: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   6177: 	}
                   6178:     } else {
                   6179: 	$r->print("\n<ul>");
                   6180:     }
                   6181:     $r->print("\n</li></ul>");
                   6182: 
                   6183: }
1.423     albertel 6184: 
                   6185: =pod
                   6186: 
                   6187: =item scantron_bubble_selector
                   6188:   
                   6189:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6190:    possibly showing the existing the selected bubbles if known
1.423     albertel 6191: 
                   6192:  Arguments:
                   6193:     $r           - Apache request object
                   6194:     $scan_config - hash from &get_scantron_config()
                   6195:     $quest       - number of the bubble line to make a corrector for
                   6196:     $selected    - array of letters of previously selected bubbles
                   6197:     $lines       - if present, number of bubble lines to show
                   6198: 
                   6199: =cut
                   6200: 
1.157     albertel 6201: sub scantron_bubble_selector {
1.422     foxr     6202:     my ($r,$scan_config,$quest,@selected, $lines)=@_;
1.157     albertel 6203:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6204: 
                   6205:     my $scmode=$$scan_config{'Qon'};
                   6206:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6207: 
1.422     foxr     6208: 
                   6209:     if (!defined($lines)) {
                   6210: 	$lines = 1;
                   6211:     }
                   6212:     my $total_lines = $lines*2;
1.157     albertel 6213:     my @alphabet=('A'..'Z');
1.422     foxr     6214:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6215: 
                   6216:     for (my $l = 0; $l < $lines; $l++) {
                   6217: 	if ($l != 0) {
                   6218: 	    $r->print('<tr>');
                   6219: 	}
                   6220: 
                   6221: 	# FIXME:  This loop probably has to be considerably more clever for
                   6222: 	#  multiline bubbles: User can multibubble by having bubbles in
                   6223: 	#  several lines.  User can skip lines legitimately etc. etc.
                   6224: 
                   6225: 	for (my $i=0;$i<$max;$i++) {
                   6226: 	    $r->print("\n".'<td align="center">');
                   6227: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6228: 		$r->print('X'); 
                   6229: 		shift(@selected) ;
                   6230: 	    } else { 
                   6231: 		$r->print('&nbsp;'); 
                   6232: 	    }
                   6233: 	    $r->print('</td>');
                   6234: 	    
                   6235: 	}
                   6236: 
                   6237: 	if ($l == 0) {
                   6238: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6239: 
                   6240: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6241: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6242: 	
                   6243: 	}
                   6244: 
                   6245: 	$r->print('</tr><tr>');
                   6246: 
                   6247: 	# FIXME: This may have to be a bit more clever for
                   6248: 	#        multiline questions (different values e.g..).
                   6249: 
                   6250: 	for (my $i=0;$i<$max;$i++) {
                   6251: 	    $r->print("\n".
                   6252: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6253: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6254: 	}
                   6255: 	$r->print('</tr>');
                   6256: 
                   6257: 	    
1.157     albertel 6258:     }
1.422     foxr     6259:     $r->print('</table>');
1.157     albertel 6260: }
                   6261: 
1.423     albertel 6262: =pod
                   6263: 
                   6264: =item num_matches
                   6265: 
1.424     albertel 6266:    Counts the number of characters that are the same between the two arguments.
                   6267: 
                   6268:  Arguments:
                   6269:    $orig - CODE from the scanline
                   6270:    $code - CODE to match against
                   6271: 
                   6272:  Returns:
                   6273:    $count - integer count of the number of same characters between the
                   6274:             two arguments
                   6275: 
1.423     albertel 6276: =cut
                   6277: 
1.194     albertel 6278: sub num_matches {
                   6279:     my ($orig,$code) = @_;
                   6280:     my @code=split(//,$code);
                   6281:     my @orig=split(//,$orig);
                   6282:     my $same=0;
                   6283:     for (my $i=0;$i<scalar(@code);$i++) {
                   6284: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6285:     }
                   6286:     return $same;
                   6287: }
                   6288: 
1.423     albertel 6289: =pod
                   6290: 
                   6291: =item scantron_get_closely_matching_CODEs
                   6292: 
1.424     albertel 6293:    Cycles through all CODEs and finds the set that has the greatest
                   6294:    number of same characters as the provided CODE
                   6295: 
                   6296:  Arguments:
                   6297:    $allcodes - hash ref returned by &get_codes()
                   6298:    $CODE     - CODE from the current scanline
                   6299: 
                   6300:  Returns:
                   6301:    2 element list
                   6302:     - first elements is number of how closely matching the best fit is 
                   6303:       (5 means best set has 5 matching characters)
                   6304:     - second element is an arrary ref containing the set of valid CODEs
                   6305:       that best fit the passed in CODE
                   6306: 
1.423     albertel 6307: =cut
                   6308: 
1.194     albertel 6309: sub scantron_get_closely_matching_CODEs {
                   6310:     my ($allcodes,$CODE)=@_;
                   6311:     my @CODEs;
                   6312:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6313: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6314:     }
                   6315: 
                   6316:     return ($#CODEs,$CODEs[-1]);
                   6317: }
                   6318: 
1.423     albertel 6319: =pod
                   6320: 
                   6321: =item get_codes
                   6322: 
1.424     albertel 6323:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6324:    set of remembered CODEs.
                   6325: 
                   6326:  Arguments:
                   6327:   $old_name - name of the set of remembered CODEs
                   6328:   $cdom     - domain of the course
                   6329:   $cnum     - internal course name
                   6330: 
                   6331:  Returns:
                   6332:   %allcodes - keys are the valid CODEs, values are all 1
                   6333: 
1.423     albertel 6334: =cut
                   6335: 
1.194     albertel 6336: sub get_codes {
1.280     foxr     6337:     my ($old_name, $cdom, $cnum) = @_;
                   6338:     if (!$old_name) {
                   6339: 	$old_name=$env{'form.scantron_CODElist'};
                   6340:     }
                   6341:     if (!$cdom) {
                   6342: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6343:     }
                   6344:     if (!$cnum) {
                   6345: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6346:     }
1.278     albertel 6347:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6348: 				    $cdom,$cnum);
                   6349:     my %allcodes;
                   6350:     if ($result{"type\0$old_name"} eq 'number') {
                   6351: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6352:     } else {
                   6353: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6354:     }
1.194     albertel 6355:     return %allcodes;
                   6356: }
                   6357: 
1.423     albertel 6358: =pod
                   6359: 
                   6360: =item scantron_validate_CODE
                   6361: 
1.424     albertel 6362:    Validates all scanlines in the selected file to not have any
                   6363:    invalid or underspecified CODEs and that none of the codes are
                   6364:    duplicated if this was requested.
                   6365: 
1.423     albertel 6366: =cut
                   6367: 
1.157     albertel 6368: sub scantron_validate_CODE {
                   6369:     my ($r,$currentphase) = @_;
1.257     albertel 6370:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6371:     if ($scantron_config{'CODElocation'} &&
                   6372: 	$scantron_config{'CODEstart'} &&
                   6373: 	$scantron_config{'CODElength'}) {
1.257     albertel 6374: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6375: 	    &FIXME_blow_up()
                   6376: 	}
                   6377:     } else {
                   6378: 	return (0,$currentphase+1);
                   6379:     }
                   6380:     
                   6381:     my %usedCODEs;
                   6382: 
1.194     albertel 6383:     my %allcodes=&get_codes();
1.186     albertel 6384: 
                   6385:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6386:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6387: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6388: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6389: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6390: 						 $scan_data);
                   6391: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6392: 	my $error=0;
1.224     albertel 6393: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6394: 	    &scantron_get_correction($r,$i,$scan_record,
                   6395: 				     \%scantron_config,
                   6396: 				     $line,'incorrectCODE',\%allcodes);
                   6397: 	    return(1,$currentphase);
                   6398: 	}
1.221     albertel 6399: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6400: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6401: 	    &scantron_get_correction($r,$i,$scan_record,
                   6402: 				     \%scantron_config,
1.194     albertel 6403: 				     $line,'incorrectCODE',\%allcodes);
                   6404: 	    return(1,$currentphase);
1.186     albertel 6405: 	}
1.214     albertel 6406: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6407: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6408: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6409: 	    &scantron_get_correction($r,$i,$scan_record,
                   6410: 				     \%scantron_config,
1.194     albertel 6411: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6412: 	    return(1,$currentphase);
1.186     albertel 6413: 	}
1.194     albertel 6414: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6415:     }
1.157     albertel 6416:     return (0,$currentphase+1);
                   6417: }
                   6418: 
1.423     albertel 6419: =pod
                   6420: 
                   6421: =item scantron_validate_doublebubble
                   6422: 
1.424     albertel 6423:    Validates all scanlines in the selected file to not have any
                   6424:    bubble lines with multiple bubbles marked.
                   6425: 
1.423     albertel 6426: =cut
                   6427: 
1.157     albertel 6428: sub scantron_validate_doublebubble {
                   6429:     my ($r,$currentphase) = @_;
                   6430:     #get student info
                   6431:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6432:     my %idmap=&username_to_idmap($classlist);
                   6433: 
                   6434:     #get scantron line setup
1.257     albertel 6435:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6436:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6437:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6438: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6439: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6440: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6441: 						 $scan_data);
                   6442: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6443: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6444: 				 'doublebubble',
                   6445: 				 $$scan_record{'scantron.doubleerror'});
                   6446:     	return (1,$currentphase);
                   6447:     }
                   6448:     return (0,$currentphase+1);
                   6449: }
                   6450: 
1.423     albertel 6451: =pod
                   6452: 
                   6453: =item scantron_get_maxbubble
                   6454: 
1.424     albertel 6455:    Returns the maximum number of bubble lines that are expected to
                   6456:    occur. Does this by walking the selected sequence rendering the
                   6457:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6458:    for what the current value of the problem counter is.
                   6459: 
                   6460:    Caches the result to $env{'form.scantron_maxbubble'}
                   6461: 
1.423     albertel 6462: =cut
                   6463: 
1.330     albertel 6464: sub scantron_get_maxbubble {    
1.257     albertel 6465:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6466: 	$env{'form.scantron_maxbubble'}) {
                   6467: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6468:     }
1.330     albertel 6469: 
1.191     albertel 6470:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6471:     my (undef,undef,$sequence)=
1.257     albertel 6472: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6473: 
1.191     albertel 6474:     my $map=$navmap->getResourceByUrl($sequence);
                   6475:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6476: 
                   6477:     &Apache::lonxml::clear_problem_counter();
                   6478: 
1.191     albertel 6479:     foreach my $resource (@resources) {
1.330     albertel 6480: 	my $result=&Apache::lonnet::ssi($resource->src(),
                   6481: 					('symb' => $resource->symb()));
1.191     albertel 6482:     }
                   6483:     &Apache::lonnet::delenv('scantron\.');
1.330     albertel 6484:     $env{'form.scantron_maxbubble'} =
                   6485: 	&Apache::lonxml::get_problem_counter()-1;
                   6486: 
1.257     albertel 6487:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6488: }
                   6489: 
1.423     albertel 6490: =pod
                   6491: 
                   6492: =item scantron_validate_missingbubbles
                   6493: 
1.424     albertel 6494:    Validates all scanlines in the selected file to not have any
                   6495:    bubble lines with missing bubbles that haven't been verified as missing.
                   6496: 
1.423     albertel 6497: =cut
                   6498: 
1.157     albertel 6499: sub scantron_validate_missingbubbles {
                   6500:     my ($r,$currentphase) = @_;
                   6501:     #get student info
                   6502:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6503:     my %idmap=&username_to_idmap($classlist);
                   6504: 
                   6505:     #get scantron line setup
1.257     albertel 6506:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6507:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6508:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6509:     if (!$max_bubble) { $max_bubble=2**31; }
                   6510:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6511: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6512: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6513: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6514: 						 $scan_data);
                   6515: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6516: 	my @to_correct;
                   6517: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6518: 	    if ($missing > $max_bubble) { next; }
                   6519: 	    push(@to_correct,$missing);
                   6520: 	}
                   6521: 	if (@to_correct) {
                   6522: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6523: 				     $line,'missingbubble',\@to_correct);
                   6524: 	    return (1,$currentphase);
                   6525: 	}
                   6526: 
                   6527:     }
                   6528:     return (0,$currentphase+1);
                   6529: }
                   6530: 
1.423     albertel 6531: =pod
                   6532: 
                   6533: =item scantron_process_students
                   6534: 
                   6535:    Routine that does the actual grading of the bubble sheet information.
                   6536: 
                   6537:    The parsed scanline hash is added to %env 
                   6538: 
                   6539:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6540:    foreach resource , with the form data of
                   6541: 
                   6542: 	'submitted'     =>'scantron' 
                   6543: 	'grade_target'  =>'grade',
                   6544: 	'grade_username'=> username of student
                   6545: 	'grade_domain'  => domain of student
                   6546: 	'grade_courseid'=> of course
                   6547: 	'grade_symb'    => symb of resource to grade
                   6548: 
                   6549:     This triggers a grading pass. The problem grading code takes care
                   6550:     of converting the bubbled letter information (now in %env) into a
                   6551:     valid submission.
                   6552: 
                   6553: =cut
                   6554: 
1.82      albertel 6555: sub scantron_process_students {
1.75      albertel 6556:     my ($r) = @_;
1.257     albertel 6557:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6558:     my ($symb)=&get_symb($r);
1.81      albertel 6559:     if (!$symb) {return '';}
1.324     albertel 6560:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6561: 
1.257     albertel 6562:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6563:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6564:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6565:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6566:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6567:     my $map=$navmap->getResourceByUrl($sequence);
                   6568:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6569: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6570:     my $result= <<SCANTRONFORM;
1.81      albertel 6571: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6572:   <input type="hidden" name="command" value="scantron_configphase" />
                   6573:   $default_form_data
                   6574: SCANTRONFORM
1.82      albertel 6575:     $r->print($result);
                   6576: 
                   6577:     my @delayqueue;
1.140     albertel 6578:     my %completedstudents;
                   6579:     
1.200     albertel 6580:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6581:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6582:  				    'Scantron Progress',$count,
1.195     albertel 6583: 				    'inline',undef,'scantronupload');
1.140     albertel 6584:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6585: 					  'Processing first student');
                   6586:     my $start=&Time::HiRes::time();
1.158     albertel 6587:     my $i=-1;
1.200     albertel 6588:     my ($uname,$udom,$started);
1.157     albertel 6589:     while ($i<$scanlines->{'count'}) {
                   6590:  	($uname,$udom)=('','');
                   6591:  	$i++;
1.200     albertel 6592:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6593:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 6594: 	if ($started) {
                   6595: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   6596: 						     'last student');
                   6597: 	}
                   6598: 	$started=1;
1.157     albertel 6599:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6600:  						 $scan_data);
                   6601:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   6602:  					      \%idmap,$i)) {
                   6603:   	    &scantron_add_delay(\@delayqueue,$line,
                   6604:  				'Unable to find a student that matches',1);
                   6605:  	    next;
                   6606:   	}
                   6607:  	if (exists $completedstudents{$uname}) {
                   6608:  	    &scantron_add_delay(\@delayqueue,$line,
                   6609:  				'Student '.$uname.' has multiple sheets',2);
                   6610:  	    next;
                   6611:  	}
                   6612:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 6613: 
                   6614: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 6615:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 6616: 
                   6617: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   6618: 	    &scantron_putfile($scanlines,$scan_data);
                   6619: 	}
1.161     albertel 6620: 	
                   6621: 	my $i=0;
1.83      albertel 6622: 	foreach my $resource (@resources) {
1.85      albertel 6623: 	    $i++;
1.193     albertel 6624: 	    my %form=('submitted'     =>'scantron',
                   6625: 		      'grade_target'  =>'grade',
                   6626: 		      'grade_username'=>$uname,
                   6627: 		      'grade_domain'  =>$udom,
1.257     albertel 6628: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 6629: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 6630: 	    if (exists($scan_record->{'scantron.CODE'})
                   6631: 		&& 
                   6632: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 6633: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 6634: 	    } else {
                   6635: 		$form{'CODE'}='';
1.193     albertel 6636: 	    }
                   6637: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 6638: 	    if ($result ne '') {
                   6639: 		&Apache::lonnet::logthis("scantron grading error -> $result");
1.257     albertel 6640: 		&Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
1.227     albertel 6641: 	    }
1.213     albertel 6642: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 6643: 	}
1.140     albertel 6644: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 6645: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 6646:     } continue {
1.330     albertel 6647: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 6648: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 6649:     }
1.140     albertel 6650:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 6651: #    my $lasttime = &Time::HiRes::time()-$start;
                   6652: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 6653: 
1.200     albertel 6654:     $r->print("</form>");
1.324     albertel 6655:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 6656:     return '';
1.75      albertel 6657: }
1.157     albertel 6658: 
1.423     albertel 6659: =pod
                   6660: 
                   6661: =item scantron_upload_scantron_data
                   6662: 
                   6663:     Creates the screen for adding a new bubble sheet data file to a course.
                   6664: 
                   6665: =cut
                   6666: 
1.157     albertel 6667: sub scantron_upload_scantron_data {
                   6668:     my ($r)=@_;
1.257     albertel 6669:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 6670:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 6671: 							  'domainid',
                   6672: 							  'coursename');
1.257     albertel 6673:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 6674: 						   'domainid');
1.324     albertel 6675:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 6676:     $r->print(<<UPLOAD);
                   6677: <script type="text/javascript" language="javascript">
                   6678:     function checkUpload(formname) {
                   6679: 	if (formname.upfile.value == "") {
                   6680: 	    alert("Please use the browse button to select a file from your local directory.");
                   6681: 	    return false;
                   6682: 	}
                   6683: 	formname.submit();
                   6684:     }
                   6685: </script>
                   6686: 
                   6687: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 6688: $default_form_data
1.181     albertel 6689: <table>
                   6690: <tr><td>$select_link </td></tr>
                   6691: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   6692: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   6693: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   6694: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   6695: </table>
1.157     albertel 6696: <input name='command' value='scantronupload_save' type='hidden' />
                   6697: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   6698: </form>
                   6699: UPLOAD
                   6700:     return '';
                   6701: }
                   6702: 
1.423     albertel 6703: =pod
                   6704: 
                   6705: =item scantron_upload_scantron_data_save
                   6706: 
                   6707:    Adds a provided bubble information data file to the course if user
                   6708:    has the correct privileges to do so.  
                   6709: 
                   6710: =cut
                   6711: 
1.157     albertel 6712: sub scantron_upload_scantron_data_save {
                   6713:     my($r)=@_;
1.324     albertel 6714:     my ($symb)=&get_symb($r,1);
1.182     albertel 6715:     my $doanotherupload=
                   6716: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   6717: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   6718: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   6719: 	'</form>'."\n";
1.257     albertel 6720:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 6721: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 6722: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 6723: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 6724: 	if ($symb) {
1.324     albertel 6725: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 6726: 	} else {
                   6727: 	    $r->print($doanotherupload);
                   6728: 	}
1.162     albertel 6729: 	return '';
                   6730:     }
1.257     albertel 6731:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       6732:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 6733:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 6734:     #FIXME
                   6735:     #copied from lonnet::userfileupload()
                   6736:     #make that function able to target a specified course
                   6737:     # Replace Windows backslashes by forward slashes
                   6738:     $fname=~s/\\/\//g;
                   6739:     # Get rid of everything but the actual filename
                   6740:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   6741:     # Replace spaces by underscores
                   6742:     $fname=~s/\s+/\_/g;
                   6743:     # Replace all other weird characters by nothing
                   6744:     $fname=~s/[^\w\.\-]//g;
                   6745:     # See if there is anything left
                   6746:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       6747:     my $uploadedfile=$fname;
1.157     albertel 6748:     $fname='scantron_orig_'.$fname;
1.257     albertel 6749:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 6750: 	$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 6751:     } else {
1.275     albertel 6752: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 6753: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 6754: 	    $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 6755: 	} else {
1.398     albertel 6756: 	    $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 6757: 	}
                   6758:     }
1.174     albertel 6759:     if ($symb) {
1.209     ng       6760: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 6761:     } else {
1.182     albertel 6762: 	$r->print($doanotherupload);
1.174     albertel 6763:     }
1.157     albertel 6764:     return '';
                   6765: }
                   6766: 
1.423     albertel 6767: =pod
                   6768: 
                   6769: =item valid_file
                   6770: 
1.424     albertel 6771:    Validates that the requested bubble data file exists in the course.
1.423     albertel 6772: 
                   6773: =cut
                   6774: 
1.202     albertel 6775: sub valid_file {
                   6776:     my ($requested_file)=@_;
                   6777:     foreach my $filename (sort(&scantron_filenames())) {
                   6778: 	if ($requested_file eq $filename) { return 1; }
                   6779:     }
                   6780:     return 0;
                   6781: }
                   6782: 
1.423     albertel 6783: =pod
                   6784: 
                   6785: =item scantron_download_scantron_data
                   6786: 
                   6787:    Shows a list of the three internal files (original, corrected,
                   6788:    skipped) for a specific bubble sheet data file that exists in the
                   6789:    course.
                   6790: 
                   6791: =cut
                   6792: 
1.202     albertel 6793: sub scantron_download_scantron_data {
                   6794:     my ($r)=@_;
1.324     albertel 6795:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 6796:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6797:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6798:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 6799:     if (! &valid_file($file)) {
                   6800: 	$r->print(<<ERROR);
                   6801: 	<p>
                   6802: 	    The requested file name was invalid.
                   6803:         </p>
                   6804: ERROR
1.324     albertel 6805: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 6806: 	return;
                   6807:     }
                   6808:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   6809:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   6810:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   6811:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   6812:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   6813:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   6814:     $r->print(<<DOWNLOAD);
                   6815:     <p>
                   6816: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   6817:     </p>
                   6818:     <p>
                   6819: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   6820:     </p>
                   6821:     <p>
                   6822: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   6823:     </p>
                   6824: DOWNLOAD
1.324     albertel 6825:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 6826:     return '';
                   6827: }
1.157     albertel 6828: 
1.423     albertel 6829: =pod
                   6830: 
                   6831: =back
                   6832: 
                   6833: =cut
                   6834: 
1.75      albertel 6835: #-------- end of section for handling grading scantron forms -------
                   6836: #
                   6837: #-------------------------------------------------------------------
                   6838: 
1.72      ng       6839: #-------------------------- Menu interface -------------------------
                   6840: #
                   6841: #--- Show a Grading Menu button - Calls the next routine ---
                   6842: sub show_grading_menu_form {
1.324     albertel 6843:     my ($symb)=@_;
1.125     ng       6844:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 6845: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 6846: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       6847: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   6848: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   6849: 	'</form>'."\n";
                   6850:     return $result;
                   6851: }
                   6852: 
1.77      ng       6853: # -- Retrieve choices for grading form
                   6854: sub savedState {
                   6855:     my %savedState = ();
1.257     albertel 6856:     if ($env{'form.saveState'}) {
                   6857: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       6858: 	    my ($key,$value) = split(/=/,$_,2);
                   6859: 	    $savedState{$key} = $value;
                   6860: 	}
                   6861:     }
                   6862:     return \%savedState;
                   6863: }
1.76      ng       6864: 
1.72      ng       6865: #--- Displays the main menu page -------
                   6866: sub gradingmenu {
                   6867:     my ($request) = @_;
1.324     albertel 6868:     my ($symb)=&get_symb($request);
1.72      ng       6869:     if (!$symb) {return '';}
1.76      ng       6870:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       6871: 
                   6872:     $request->print(<<GRADINGMENUJS);
                   6873: <script type="text/javascript" language="javascript">
1.116     ng       6874:     function checkChoice(formname,val,cmdx) {
                   6875: 	if (val <= 2) {
                   6876: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       6877: 	    var cmdsave = cmd;
1.116     ng       6878: 	} else {
                   6879: 	    cmd = cmdx;
1.118     ng       6880: 	    cmdsave = 'submission';
1.116     ng       6881: 	}
                   6882: 	formname.command.value = cmd;
1.118     ng       6883: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 6884: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       6885: 	if (val < 5) formname.submit();
                   6886: 	if (val == 5) {
1.72      ng       6887: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   6888: 	    formname.submit();
                   6889: 	}
1.238     albertel 6890: 	if (val < 7) formname.submit();
1.72      ng       6891:     }
                   6892: 
                   6893:     function checkReceiptNo(formname,nospace) {
                   6894: 	var receiptNo = formname.receipt.value;
                   6895: 	var checkOpt = false;
                   6896: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   6897: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   6898: 	if (checkOpt) {
                   6899: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   6900: 	    formname.receipt.value = "";
                   6901: 	    formname.receipt.focus();
                   6902: 	    return false;
                   6903: 	}
                   6904: 	return true;
                   6905:     }
                   6906: </script>
                   6907: GRADINGMENUJS
1.118     ng       6908:     &commonJSfunctions($request);
1.398     albertel 6909:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
1.324     albertel 6910:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       6911:     $result.=$table;
1.76      ng       6912:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       6913:     my $savedState = &savedState();
1.118     ng       6914:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       6915:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       6916:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       6917:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       6918: 
                   6919:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 6920: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       6921: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   6922: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       6923: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       6924: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       6925: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       6926: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   6927: 
1.326     albertel 6928:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   6929: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
1.72      ng       6930: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       6931: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   6932: 
1.326     albertel 6933:     $result.='<table width="100%" border="0">';
1.116     ng       6934:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.167     sakharuk 6935: 	'&nbsp;'.&mt('Select Section').': <select name="section">'."\n";
1.116     ng       6936:     if (ref($sections)) {
1.155     albertel 6937: 	foreach (sort (@$sections)) {
                   6938: 	    $result.='<option value="'.$_.'" '.
1.401     albertel 6939: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
1.155     albertel 6940: 	}
1.116     ng       6941:     }
1.401     albertel 6942:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.116     ng       6943: 
1.401     albertel 6944:     $result.=&mt('Student Status').':'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
1.72      ng       6945: 
1.116     ng       6946:     $result.='</td></tr>';
                   6947: 
1.288     albertel 6948:     $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
1.118     ng       6949: 	'<input type="radio" name="radioChoice" value="submission" '.
1.401     albertel 6950: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 6951: 	'</label> <select name="submitonly">'.
1.145     albertel 6952: 	'<option value="yes" '.
1.401     albertel 6953: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
1.301     albertel 6954: 	'<option value="queued" '.
1.401     albertel 6955: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
1.145     albertel 6956: 	'<option value="graded" '.
1.401     albertel 6957: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 6958: 	'<option value="incorrect" '.
1.401     albertel 6959: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 6960: 	'<option value="all" '.
1.401     albertel 6961: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       6962: 
1.116     ng       6963:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.288     albertel 6964: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.401     albertel 6965: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
1.288     albertel 6966: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       6967: 
1.118     ng       6968:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
1.288     albertel 6969: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.401     albertel 6970: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
1.288     albertel 6971: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       6972: 
1.116     ng       6973:     $result.='<tr bgcolor="#ffffe6"><td><br />'.
1.126     ng       6974: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       6975: 	'</td></tr></table>'."\n";
                   6976: 
                   6977:     $result.='</td><td valign="top">';
                   6978: 
1.326     albertel 6979:     $result.='<table width="100%" border="0">';
1.116     ng       6980:     $result.='<tr bgcolor="#ffffe6"><td>'.
1.184     www      6981: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   6982: 	' '.&mt('scores from file').' </td></tr>'."\n";
1.72      ng       6983: 
1.404     www      6984:     $result.='<tr bgcolor="#ffffe6"><td>'.
                   6985:         '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
                   6986:         ' '.&mt('clicker file').' </td></tr>'."\n";
1.400     www      6987: 
1.75      albertel 6988:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.116     ng       6989: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
1.184     www      6990: 	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
1.75      albertel 6991: 
1.257     albertel 6992:     if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
1.72      ng       6993: 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.184     www      6994: 	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   6995: 	    ' '.&mt('receipt').': '.
1.257     albertel 6996: 	    &Apache::lonnet::recprefix($env{'request.course.id'}).
1.326     albertel 6997: 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
1.72      ng       6998: 	    '</td></tr>'."\n";
                   6999:     } 
1.238     albertel 7000:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7001: 	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   7002: 	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
1.279     albertel 7003:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7004: 	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   7005: 	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
1.44      ng       7006: 
1.401     albertel 7007:     $result.='</table>'."\n".
1.72      ng       7008: 	'</td></tr></table>'."\n".
1.401     albertel 7009: 	'</td></tr></table></form>'."\n";
1.44      ng       7010:     return $result;
1.2       albertel 7011: }
                   7012: 
1.285     albertel 7013: sub reset_perm {
                   7014:     undef(%perm);
                   7015: }
                   7016: 
                   7017: sub init_perm {
                   7018:     &reset_perm();
1.300     albertel 7019:     foreach my $test_perm ('vgr','mgr','opa') {
                   7020: 
                   7021: 	my $scope = $env{'request.course.id'};
                   7022: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7023: 
                   7024: 	    $scope .= '/'.$env{'request.course.sec'};
                   7025: 	    if ( $perm{$test_perm}=
                   7026: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7027: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7028: 	    } else {
                   7029: 		delete($perm{$test_perm});
                   7030: 	    }
1.285     albertel 7031: 	}
                   7032:     }
                   7033: }
                   7034: 
1.400     www      7035: sub gather_clicker_ids {
1.408     albertel 7036:     my %clicker_ids;
1.400     www      7037: 
                   7038:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7039: 
                   7040:     # Set up a couple variables.
1.407     albertel 7041:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7042:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.400     www      7043: 
1.407     albertel 7044:     foreach my $student (keys(%$classlist)) {
1.400     www      7045: 
1.407     albertel 7046:         my $username = $classlist->{$student}->[$username_idx];
                   7047:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7048:         my $clickers =
1.408     albertel 7049: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7050:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7051:             $id=~s/^[\#0]+//;
1.421     www      7052:             $id=~s/[\-\:]//g;
1.407     albertel 7053:             if (exists($clicker_ids{$id})) {
1.408     albertel 7054: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7055:             } else {
1.408     albertel 7056: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7057:             }
                   7058:         }
                   7059:     }
1.407     albertel 7060:     return %clicker_ids;
1.400     www      7061: }
                   7062: 
1.402     www      7063: sub gather_adv_clicker_ids {
1.408     albertel 7064:     my %clicker_ids;
1.402     www      7065:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7066:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7067:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7068:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7069:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7070:             my ($puname,$pudom)=split(/\:/,$person);
                   7071:             my $clickers =
1.408     albertel 7072: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7073:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7074: 		$id=~s/^[\#0]+//;
1.421     www      7075:                 $id=~s/[\-\:]//g;
1.408     albertel 7076: 		if (exists($clicker_ids{$id})) {
                   7077: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7078: 		} else {
                   7079: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7080: 		}
1.405     www      7081:             }
1.402     www      7082:         }
                   7083:     }
1.407     albertel 7084:     return %clicker_ids;
1.402     www      7085: }
                   7086: 
1.413     www      7087: sub clicker_grading_parameters {
                   7088:     return ('gradingmechanism' => 'scalar',
                   7089:             'upfiletype' => 'scalar',
                   7090:             'specificid' => 'scalar',
                   7091:             'pcorrect' => 'scalar',
                   7092:             'pincorrect' => 'scalar');
                   7093: }
                   7094: 
1.400     www      7095: sub process_clicker {
                   7096:     my ($r)=@_;
                   7097:     my ($symb)=&get_symb($r);
                   7098:     if (!$symb) {return '';}
                   7099:     my $result=&checkforfile_js();
                   7100:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7101:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7102:     $result.=$table;
                   7103:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7104:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7105:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7106:         '.</b></td></tr>'."\n";
                   7107:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7108: # Attempt to restore parameters from last session, set defaults if not present
                   7109:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7110:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7111:                                                  \%Saveable_Parameters);
                   7112:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7113:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7114:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7115:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7116: 
                   7117:     my %checked;
                   7118:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7119:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7120:           $checked{$gradingmechanism}="checked='checked'";
                   7121:        }
                   7122:     }
                   7123: 
1.400     www      7124:     my $upload=&mt("Upload File");
                   7125:     my $type=&mt("Type");
1.402     www      7126:     my $attendance=&mt("Award points just for participation");
                   7127:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7128:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7129:     my $pcorrect=&mt("Percentage points for correct solution");
                   7130:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7131:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7132: 						   ('iclicker' => 'i>clicker',
                   7133:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7134:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7135:     $result.=<<ENDUPFORM;
1.402     www      7136: <script type="text/javascript">
                   7137: function sanitycheck() {
                   7138: // Accept only integer percentages
                   7139:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7140:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7141: // Find out grading choice
                   7142:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7143:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7144:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7145:       }
                   7146:    }
                   7147: // By default, new choice equals user selection
                   7148:    newgradingchoice=gradingchoice;
                   7149: // Not good to give more points for false answers than correct ones
                   7150:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7151:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7152:    }
                   7153: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7154:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7155:       document.forms.gradesupload.pcorrect.value=100;
                   7156:       document.forms.gradesupload.pincorrect.value=100;
                   7157:    }
                   7158: // If the values are different, cannot be attendance only
                   7159:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7160:        (gradingchoice=='attendance')) {
                   7161:        newgradingchoice='personnel';
                   7162:    }
                   7163: // Change grading choice to new one
                   7164:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7165:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7166:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7167:       } else {
                   7168:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7169:       }
                   7170:    }
                   7171: // Remember the old state
                   7172:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7173: }
                   7174: </script>
1.400     www      7175: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7176: <input type="hidden" name="symb" value="$symb" />
                   7177: <input type="hidden" name="command" value="processclickerfile" />
                   7178: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7179: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7180: <input type="file" name="upfile" size="50" />
                   7181: <br /><label>$type: $selectform</label>
1.413     www      7182: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
                   7183: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
                   7184: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
1.414     www      7185: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7186: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7187: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7188: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7189: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7190: </form>
                   7191: ENDUPFORM
                   7192:     $result.='</td></tr></table>'."\n".
                   7193:              '</td></tr></table><br /><br />'."\n";
                   7194:     $result.=&show_grading_menu_form($symb);
                   7195:     return $result;
                   7196: }
                   7197: 
                   7198: sub process_clicker_file {
                   7199:     my ($r)=@_;
                   7200:     my ($symb)=&get_symb($r);
                   7201:     if (!$symb) {return '';}
1.413     www      7202: 
                   7203:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7204:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7205:                                               \%Saveable_Parameters);
                   7206: 
1.400     www      7207:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7208:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7209: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7210: 	return $result.&show_grading_menu_form($symb);
1.404     www      7211:     }
1.407     albertel 7212:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7213:     my %correct_ids;
1.404     www      7214:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7215: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7216:     }
                   7217:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7218: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7219: 	   $correct_id=~tr/a-z/A-Z/;
                   7220: 	   $correct_id=~s/\s//gs;
                   7221: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7222:            $correct_id=~s/[\-\:]//g;
1.414     www      7223:            if ($correct_id) {
                   7224: 	      $correct_ids{$correct_id}='specified';
                   7225:            }
                   7226:         }
1.400     www      7227:     }
1.404     www      7228:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7229: 	$result.=&mt('Score based on attendance only');
1.404     www      7230:     } else {
1.408     albertel 7231: 	my $number=0;
1.411     www      7232: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7233: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7234: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7235: 	    if ($correct_ids{$id} eq 'specified') {
                   7236: 		$result.=&mt('specified');
                   7237: 	    } else {
                   7238: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7239: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7240: 	    }
                   7241: 	    $number++;
                   7242: 	}
1.411     www      7243:         $result.="</p>\n";
1.408     albertel 7244: 	if ($number==0) {
                   7245: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7246: 	    return $result.&show_grading_menu_form($symb);
                   7247: 	}
1.404     www      7248:     }
1.405     www      7249:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7250:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7251: 		     '<span class="LC_error">',
                   7252: 		     '</span>',
                   7253: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7254:         return $result.&show_grading_menu_form($symb);
                   7255:     }
1.410     www      7256: 
                   7257: # Were able to get all the info needed, now analyze the file
                   7258: 
1.411     www      7259:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7260:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7261:     my $heading=&mt('Scanning clicker file');
                   7262:     $result.=(<<ENDHEADER);
                   7263: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7264: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7265: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7266: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7267: <input type="hidden" name="symb" value="$symb" />
                   7268: <input type="hidden" name="command" value="assignclickergrades" />
                   7269: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7270: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7271: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7272: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7273: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7274: ENDHEADER
1.408     albertel 7275:     my %responses;
                   7276:     my @questiontitles;
1.405     www      7277:     my $errormsg='';
                   7278:     my $number=0;
                   7279:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7280: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7281:     }
1.419     www      7282:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7283:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7284:     }
1.411     www      7285:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7286:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   7287:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7288:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7289:              '<br />';
1.414     www      7290: # Remember Question Titles
                   7291: # FIXME: Possibly need delimiter other than ":"
                   7292:     for (my $i=0;$i<$number;$i++) {
                   7293:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7294:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7295:     }
1.411     www      7296:     my $correct_count=0;
                   7297:     my $student_count=0;
                   7298:     my $unknown_count=0;
1.414     www      7299: # Match answers with usernames
                   7300: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7301:     foreach my $id (keys(%responses)) {
1.410     www      7302:        if ($correct_ids{$id}) {
1.414     www      7303:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7304:           $correct_count++;
1.410     www      7305:        } elsif ($clicker_ids{$id}) {
                   7306:           $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7307:           $student_count++;
1.410     www      7308:        } else {
1.411     www      7309:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7310:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7311:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7312:                    "\n".&mt("Domain").": ".
                   7313:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7314:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7315:           $unknown_count++;
1.410     www      7316:        }
1.405     www      7317:     }
1.412     www      7318:     $result.='<hr />'.
                   7319:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7320:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7321:        if ($correct_count==0) {
                   7322:           $errormsg.="Found no correct answers answers for grading!";
                   7323:        } elsif ($correct_count>1) {
1.414     www      7324:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7325:        }
                   7326:     }
1.428   ! www      7327:     if ($number<1) {
        !          7328:        $errormsg.="Found no questions.";
        !          7329:     }
1.412     www      7330:     if ($errormsg) {
                   7331:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7332:     } else {
                   7333:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7334:     }
                   7335:     $result.='</form></td></tr></table>'."\n".
1.410     www      7336:              '</td></tr></table><br /><br />'."\n";
1.404     www      7337:     return $result.&show_grading_menu_form($symb);
1.400     www      7338: }
                   7339: 
1.405     www      7340: sub iclicker_eval {
1.406     www      7341:     my ($questiontitles,$responses)=@_;
1.405     www      7342:     my $number=0;
                   7343:     my $errormsg='';
                   7344:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7345:         my %components=&Apache::loncommon::record_sep($line);
                   7346:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7347: 	if ($entries[0] eq 'Question') {
                   7348: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7349: 		$$questiontitles[$number]=$entries[$i];
                   7350: 		$number++;
                   7351: 	    }
                   7352: 	}
                   7353: 	if ($entries[0]=~/^\#/) {
                   7354: 	    my $id=$entries[0];
                   7355: 	    my @idresponses;
                   7356: 	    $id=~s/^[\#0]+//;
                   7357: 	    for (my $i=0;$i<$number;$i++) {
                   7358: 		my $idx=3+$i*6;
                   7359: 		push(@idresponses,$entries[$idx]);
                   7360: 	    }
                   7361: 	    $$responses{$id}=join(',',@idresponses);
                   7362: 	}
1.405     www      7363:     }
                   7364:     return ($errormsg,$number);
                   7365: }
                   7366: 
1.419     www      7367: sub interwrite_eval {
                   7368:     my ($questiontitles,$responses)=@_;
                   7369:     my $number=0;
                   7370:     my $errormsg='';
1.420     www      7371:     my $skipline=1;
                   7372:     my $questionnumber=0;
                   7373:     my %idresponses=();
1.419     www      7374:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   7375:         my %components=&Apache::loncommon::record_sep($line);
                   7376:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      7377:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   7378:         if ($entries[1] eq 'Response') { $skipline=1; }
                   7379:         next if $skipline;
                   7380:         if ($entries[0]!=$questionnumber) {
                   7381:            $questionnumber=$entries[0];
                   7382:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   7383:            $number++;
1.419     www      7384:         }
1.420     www      7385:         my $id=$entries[4];
                   7386:         $id=~s/^[\#0]+//;
1.421     www      7387:         $id=~s/^v\d*\://i;
                   7388:         $id=~s/[\-\:]//g;
1.420     www      7389:         $idresponses{$id}[$number]=$entries[6];
                   7390:     }
                   7391:     foreach my $id (keys %idresponses) {
                   7392:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   7393:        $$responses{$id}=~s/^\s*\,//;
1.419     www      7394:     }
                   7395:     return ($errormsg,$number);
                   7396: }
                   7397: 
1.414     www      7398: sub assign_clicker_grades {
                   7399:     my ($r)=@_;
                   7400:     my ($symb)=&get_symb($r);
                   7401:     if (!$symb) {return '';}
1.416     www      7402: # See which part we are saving to
                   7403:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   7404: # FIXME: This should probably look for the first handgradeable part
                   7405:     my $part=$$partlist[0];
                   7406: # Start screen output
1.414     www      7407:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      7408: 
1.414     www      7409:     my $heading=&mt('Assigning grades based on clicker file');
                   7410:     $result.=(<<ENDHEADER);
                   7411: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7412: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7413: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7414: ENDHEADER
                   7415: # Get correct result
                   7416: # FIXME: Possibly need delimiter other than ":"
                   7417:     my @correct=();
1.415     www      7418:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   7419:     my $number=$env{'form.number'};
                   7420:     if ($gradingmechanism ne 'attendance') {
1.414     www      7421:        foreach my $key (keys(%env)) {
                   7422:           if ($key=~/^form\.correct\:/) {
                   7423:              my @input=split(/\,/,$env{$key});
                   7424:              for (my $i=0;$i<=$#input;$i++) {
                   7425:                  if (($correct[$i]) && ($input[$i]) &&
                   7426:                      ($correct[$i] ne $input[$i])) {
                   7427:                     $result.='<br /><span class="LC_warning">'.
                   7428:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   7429:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   7430:                  } elsif ($input[$i]) {
                   7431:                     $correct[$i]=$input[$i];
                   7432:                  }
                   7433:              }
                   7434:           }
                   7435:        }
1.415     www      7436:        for (my $i=0;$i<$number;$i++) {
1.414     www      7437:           if (!$correct[$i]) {
                   7438:              $result.='<br /><span class="LC_error">'.
                   7439:                       &mt('No correct result given for question "[_1]"!',
                   7440:                           $env{'form.question:'.$i}).'</span>';
                   7441:           }
                   7442:        }
                   7443:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   7444:     }
                   7445: # Start grading
1.415     www      7446:     my $pcorrect=$env{'form.pcorrect'};
                   7447:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      7448:     my $storecount=0;
1.415     www      7449:     foreach my $key (keys(%env)) {
1.420     www      7450:        my $user='';
1.415     www      7451:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      7452:           $user=$1;
                   7453:        }
                   7454:        if ($key=~/^form\.unknown\:(.*)$/) {
                   7455:           my $id=$1;
                   7456:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   7457:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
                   7458:           }
                   7459:        }
                   7460:        if ($user) { 
1.415     www      7461:           my @answer=split(/\,/,$env{$key});
                   7462:           my $sum=0;
                   7463:           for (my $i=0;$i<$number;$i++) {
                   7464:              if ($answer[$i]) {
                   7465:                 if ($gradingmechanism eq 'attendance') {
                   7466:                    $sum+=$pcorrect;
                   7467:                 } else {
                   7468:                    if ($answer[$i] eq $correct[$i]) {
                   7469:                       $sum+=$pcorrect;
                   7470:                    } else {
                   7471:                       $sum+=$pincorrect;
                   7472:                    }
                   7473:                 }
                   7474:              }
                   7475:           }
1.416     www      7476:           my $ave=$sum/(100*$number);
                   7477: # Store
                   7478:           my ($username,$domain)=split(/\:/,$user);
                   7479:           my %grades=();
                   7480:           $grades{"resource.$part.solved"}='correct_by_override';
                   7481:           $grades{"resource.$part.awarded"}=$ave;
                   7482:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   7483:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   7484:                                                  $env{'request.course.id'},
                   7485:                                                  $domain,$username);
                   7486:           if ($returncode ne 'ok') {
                   7487:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   7488:           } else {
                   7489:              $storecount++;
                   7490:           }
1.415     www      7491:        }
                   7492:     }
                   7493: # We are done
1.416     www      7494:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   7495:              '</td></tr></table>'."\n".
1.414     www      7496:              '</td></tr></table><br /><br />'."\n";
                   7497:     return $result.&show_grading_menu_form($symb);
                   7498: }
                   7499: 
1.1       albertel 7500: sub handler {
1.41      ng       7501:     my $request=$_[0];
1.102     albertel 7502: 
1.285     albertel 7503:     &reset_perm();
1.257     albertel 7504:     if ($env{'browser.mathml'}) {
1.141     www      7505: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       7506:     } else {
1.141     www      7507: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       7508:     }
                   7509:     $request->send_http_header;
1.44      ng       7510:     return '' if $request->header_only;
1.41      ng       7511:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 7512:     my $symb=&get_symb($request,1);
1.160     albertel 7513:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   7514:     my $command=$commands[0];
                   7515:     if ($#commands > 0) {
                   7516: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   7517:     }
1.353     albertel 7518:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 7519:     if ($symb eq '' && $command eq '') {
1.257     albertel 7520: 	if ($env{'user.adv'}) {
                   7521: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   7522: 		($env{'form.codethree'})) {
                   7523: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   7524: 		    $env{'form.codethree'};
1.41      ng       7525: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   7526: 		    &Apache::lonnet::checkin($token);
                   7527: 		if ($tsymb) {
1.137     albertel 7528: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       7529: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 7530: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   7531: 					  ('grade_username' => $tuname,
                   7532: 					   'grade_domain' => $tudom,
                   7533: 					   'grade_courseid' => $tcrsid,
                   7534: 					   'grade_symb' => $tsymb)));
1.41      ng       7535: 		    } else {
1.45      ng       7536: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 7537: 		    }
1.41      ng       7538: 		} else {
1.45      ng       7539: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       7540: 		}
1.14      www      7541: 	    } else {
1.41      ng       7542: 		$request->print(&Apache::lonxml::tokeninputfield());
                   7543: 	    }
                   7544: 	}
                   7545:     } else {
1.285     albertel 7546: 	&init_perm();
1.104     albertel 7547: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 7548: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 7549: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       7550: 	    &pickStudentPage($request);
1.103     albertel 7551: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       7552: 	    &displayPage($request);
1.104     albertel 7553: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       7554: 	    &updateGradeByPage($request);
1.104     albertel 7555: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       7556: 	    &processGroup($request);
1.104     albertel 7557: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.41      ng       7558: 	    $request->print(&gradingmenu($request));
1.104     albertel 7559: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       7560: 	    $request->print(&viewgrades($request));
1.104     albertel 7561: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       7562: 	    $request->print(&processHandGrade($request));
1.106     albertel 7563: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       7564: 	    $request->print(&editgrades($request));
1.106     albertel 7565: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       7566: 	    $request->print(&verifyreceipt($request));
1.400     www      7567:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   7568:             $request->print(&process_clicker($request));
                   7569:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   7570:             $request->print(&process_clicker_file($request));
1.414     www      7571:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   7572:             $request->print(&assign_clicker_grades($request));
1.106     albertel 7573: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       7574: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 7575: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       7576: 	    $request->print(&csvupload($request));
1.106     albertel 7577: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       7578: 	    $request->print(&csvuploadmap($request));
1.246     albertel 7579: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 7580: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 7581: 		$request->print(&csvuploadoptions($request));
1.41      ng       7582: 	    } else {
1.257     albertel 7583: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   7584: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       7585: 		} else {
1.257     albertel 7586: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       7587: 		}
                   7588: 		$request->print(&csvuploadmap($request));
                   7589: 	    }
1.246     albertel 7590: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   7591: 	    $request->print(&csvuploadassign($request));
1.106     albertel 7592: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 7593: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 7594:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   7595:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 7596: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   7597: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 7598: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 7599: 	    $request->print(&scantron_process_students($request));
1.157     albertel 7600:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 7601:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   7602: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 7603:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 7604:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 7605:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   7606: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 7607:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 7608:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 7609: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 7610:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 7611: 	} elsif ($command) {
1.157     albertel 7612: 	    $request->print("Access Denied ($command)");
1.26      albertel 7613: 	}
1.2       albertel 7614:     }
1.353     albertel 7615:     $request->print(&Apache::loncommon::end_page());
1.44      ng       7616:     return '';
                   7617: }
                   7618: 
1.1       albertel 7619: 1;
                   7620: 
1.13      albertel 7621: __END__;

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