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

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

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