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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.494     albertel    4: # $Id: grades.pm,v 1.493 2007/11/16 08:50:39 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.456     banghart   38: use Apache::lonpickcode;
1.55      matthew    39: use Apache::loncoursedata;
1.362     albertel   40: use Apache::lonmsg();
1.1       albertel   41: use Apache::Constants qw(:common);
1.167     sakharuk   42: use Apache::lonlocal;
1.386     raeburn    43: use Apache::lonenc;
1.170     albertel   44: use String::Similarity;
1.359     www        45: use LONCAPA;
                     46: 
1.315     bowersj2   47: use POSIX qw(floor);
1.87      www        48: 
1.435     foxr       49: 
                     50: my %perm=();
1.447     foxr       51: 
1.44      ng         52: #
1.146     albertel   53: # --- Retrieve the parts from the metadata file.---
1.44      ng         54: sub getpartlist {
1.324     albertel   55:     my ($symb) = @_;
1.439     albertel   56: 
                     57:     my $navmap   = Apache::lonnavmaps::navmap->new();
                     58:     my $res      = $navmap->getBySymb($symb);
                     59:     my $partlist = $res->parts();
                     60:     my $url      = $res->src();
                     61:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                     62: 
1.146     albertel   63:     my @stores;
1.439     albertel   64:     foreach my $part (@{ $partlist }) {
1.146     albertel   65: 	foreach my $key (@metakeys) {
                     66: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                     67: 	}
                     68:     }
                     69:     return @stores;
1.2       albertel   70: }
                     71: 
1.44      ng         72: # --- Get the symbolic name of a problem and the url
1.324     albertel   73: sub get_symb {
1.173     albertel   74:     my ($request,$silent) = @_;
1.257     albertel   75:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                     76:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel   77:     if ($symb eq '') { 
                     78: 	if (!$silent) {
                     79: 	    $request->print("Unable to handle ambiguous references:$url:.");
                     80: 	    return ();
                     81: 	}
                     82:     }
1.418     albertel   83:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel   84:     return ($symb);
1.32      ng         85: }
                     86: 
1.129     ng         87: #--- Format fullname, username:domain if different for display
                     88: #--- Use anywhere where the student names are listed
                     89: sub nameUserString {
                     90:     my ($type,$fullname,$uname,$udom) = @_;
                     91:     if ($type eq 'header') {
1.485     albertel   92: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng         93:     } else {
1.398     albertel   94: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                     95: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng         96:     }
                     97: }
                     98: 
1.44      ng         99: #--- Get the partlist and the response type for a given problem. ---
                    100: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        101: sub response_type {
1.324     albertel  102:     my ($symb) = shift;
1.377     albertel  103: 
                    104:     my $navmap = Apache::lonnavmaps::navmap->new();
                    105:     my $res = $navmap->getBySymb($symb);
                    106:     my $partlist = $res->parts();
1.392     albertel  107:     my %vPart = 
                    108: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  109:     my (%response_types,%handgrade);
                    110:     foreach my $part (@{ $partlist }) {
1.392     albertel  111: 	next if (%vPart && !exists($vPart{$part}));
                    112: 
1.377     albertel  113: 	my @types = $res->responseType($part);
                    114: 	my @ids = $res->responseIds($part);
                    115: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    116: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    117: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    118: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    119: 				     '.handgrade',$symb);
1.41      ng        120: 	}
                    121:     }
1.377     albertel  122:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        123: }
                    124: 
1.375     albertel  125: sub flatten_responseType {
                    126:     my ($responseType) = @_;
                    127:     my @part_response_id =
                    128: 	map { 
                    129: 	    my $part = $_;
                    130: 	    map {
                    131: 		[$part,$_]
                    132: 		} sort(keys(%{ $responseType->{$part} }));
                    133: 	} sort(keys(%$responseType));
                    134:     return @part_response_id;
                    135: }
                    136: 
1.207     albertel  137: sub get_display_part {
1.324     albertel  138:     my ($partID,$symb)=@_;
1.207     albertel  139:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    140:     if (defined($display) and $display ne '') {
1.398     albertel  141: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  142:     } else {
                    143: 	$display=$partID;
                    144:     }
                    145:     return $display;
                    146: }
1.269     raeburn   147: 
1.118     ng        148: #--- Show resource title
                    149: #--- and parts and response type
                    150: sub showResourceInfo {
1.324     albertel  151:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  152:     my $col=3;
                    153:     if ($checkboxes) { $col=4; }
1.398     albertel  154:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    155:     $result .='<table border="0">';
1.324     albertel  156:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        157:     my %resptype = ();
1.122     ng        158:     my $hdgrade='no';
1.154     albertel  159:     my %partsseen;
1.375     albertel  160:     foreach my $partID (sort keys(%$responseType)) {
                    161: 	foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
                    162: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    163: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    164: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    165: 	    $result.='<tr>';
                    166: 	    if ($checkboxes) {
                    167: 		if (exists($partsseen{$partID})) {
                    168: 		    $result.="<td>&nbsp;</td>";
                    169: 		} else {
1.401     albertel  170: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  171: 		}
                    172: 		$partsseen{$partID}=1;
1.154     albertel  173: 	    }
1.375     albertel  174: 	    my $display_part=&get_display_part($partID,$symb);
1.485     albertel  175: 	    $result.='<td>'.&mt('<b>Part: </b>[_1]',$display_part).' <span class="LC_internal_info">'.
1.398     albertel  176: 		$resID.'</span></td>'.
1.485     albertel  177: 		'<td>'.&mt('<b>Type: </b>[_1]',$responsetype).'</td></tr>';
                    178: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
1.154     albertel  179: 	}
1.118     ng        180:     }
                    181:     $result.='</table>'."\n";
1.147     albertel  182:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        183: }
                    184: 
1.434     albertel  185: sub reset_caches {
                    186:     &reset_analyze_cache();
                    187:     &reset_perm();
                    188: }
                    189: 
                    190: {
                    191:     my %analyze_cache;
1.148     albertel  192: 
1.434     albertel  193:     sub reset_analyze_cache {
                    194: 	undef(%analyze_cache);
                    195:     }
                    196: 
                    197:     sub get_analyze {
                    198: 	my ($symb,$uname,$udom)=@_;
                    199: 	my $key = "$symb\0$uname\0$udom";
                    200: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
                    201: 
                    202: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    203: 	$url=&Apache::lonnet::clutter($url);
                    204: 	my $subresult=&Apache::lonnet::ssi($url,
                    205: 					   ('grade_target' => 'analyze'),
                    206: 					   ('grade_domain' => $udom),
                    207: 					   ('grade_symb' => $symb),
                    208: 					   ('grade_courseid' => 
                    209: 					    $env{'request.course.id'}),
                    210: 					   ('grade_username' => $uname));
                    211: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    212: 	my %analyze=&Apache::lonnet::str2hash($subresult);
                    213: 	return $analyze_cache{$key} = \%analyze;
                    214:     }
                    215: 
                    216:     sub get_order {
                    217: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    218: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    219: 	return $analyze->{"$partid.$respid.shown"};
                    220:     }
                    221: 
                    222:     sub get_radiobutton_correct_foil {
                    223: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    224: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    225: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
                    226: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    227: 		return $foil;
                    228: 	    }
                    229: 	}
                    230:     }
1.148     albertel  231: }
1.434     albertel  232: 
1.118     ng        233: #--- Clean response type for display
1.335     albertel  234: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    235: #        response types only.
1.118     ng        236: sub cleanRecord {
1.336     albertel  237:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    238: 	$uname,$udom) = @_;
1.398     albertel  239:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  240:     if ($response =~ /^(option|rank)$/) {
                    241: 	my %answer=&Apache::lonnet::str2hash($answer);
                    242: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    243: 	my ($toprow,$bottomrow);
                    244: 	foreach my $foil (@$order) {
                    245: 	    if ($grading{$foil} == 1) {
                    246: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    247: 	    } else {
                    248: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    249: 	    }
1.398     albertel  250: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  251: 	}
                    252: 	return '<blockquote><table border="1">'.
1.466     albertel  253: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    254: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  255: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    256:     } elsif ($response eq 'match') {
                    257: 	my %answer=&Apache::lonnet::str2hash($answer);
                    258: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    259: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    260: 	my ($toprow,$middlerow,$bottomrow);
                    261: 	foreach my $foil (@$order) {
                    262: 	    my $item=shift(@items);
                    263: 	    if ($grading{$foil} == 1) {
                    264: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  265: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  266: 	    } else {
                    267: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  268: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  269: 	    }
1.398     albertel  270: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        271: 	}
1.126     ng        272: 	return '<blockquote><table border="1">'.
1.466     albertel  273: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    274: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  275: 	    $middlerow.'</tr>'.
1.466     albertel  276: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  277: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    278:     } elsif ($response eq 'radiobutton') {
                    279: 	my %answer=&Apache::lonnet::str2hash($answer);
                    280: 	my ($toprow,$bottomrow);
1.434     albertel  281: 	my $correct = 
                    282: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    283: 	foreach my $foil (@$order) {
1.148     albertel  284: 	    if (exists($answer{$foil})) {
1.434     albertel  285: 		if ($foil eq $correct) {
1.466     albertel  286: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  287: 		} else {
1.466     albertel  288: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  289: 		}
                    290: 	    } else {
1.466     albertel  291: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  292: 	    }
1.398     albertel  293: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  294: 	}
                    295: 	return '<blockquote><table border="1">'.
1.466     albertel  296: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    297: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  298: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    299:     } elsif ($response eq 'essay') {
1.257     albertel  300: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        301: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  302: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    303: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        304: 
1.257     albertel  305: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    306: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    307: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    308: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    309: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    310: 	    $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        311: 	}
1.166     albertel  312: 	$answer =~ s-\n-<br />-g;
                    313: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  314:     } elsif ( $response eq 'organic') {
                    315: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    316: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    317: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    318: 	return $result;
1.335     albertel  319:     } elsif ( $response eq 'Task') {
                    320: 	if ( $answer eq 'SUBMITTED') {
                    321: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  322: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  323: 	    return $result;
                    324: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    325: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    326: 			       keys(%{$record}));
                    327: 	    return join('<br />',($version,@matches));
                    328: 			       
                    329: 			       
                    330: 	} else {
                    331: 	    my $result =
                    332: 		'<p>'
                    333: 		.&mt('Overall result: [_1]',
                    334: 		     $record->{$version."resource.$respid.$partid.status"})
                    335: 		.'</p>';
                    336: 	    
                    337: 	    $result .= '<ul>';
                    338: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    339: 			     keys(%{$record}));
                    340: 	    foreach my $grade (sort(@grade)) {
                    341: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    342: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    343: 				     $dim, $record->{$grade}).
                    344: 			  '</li>';
                    345: 	    }
                    346: 	    $result.='</ul>';
                    347: 	    return $result;
                    348: 	}
1.440     albertel  349:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    350: 	$answer = 
                    351: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    352: 							      $answer);
1.122     ng        353:     }
1.118     ng        354:     return $answer;
                    355: }
                    356: 
                    357: #-- A couple of common js functions
                    358: sub commonJSfunctions {
                    359:     my $request = shift;
                    360:     $request->print(<<COMMONJSFUNCTIONS);
                    361: <script type="text/javascript" language="javascript">
                    362:     function radioSelection(radioButton) {
                    363: 	var selection=null;
                    364: 	if (radioButton.length > 1) {
                    365: 	    for (var i=0; i<radioButton.length; i++) {
                    366: 		if (radioButton[i].checked) {
                    367: 		    return radioButton[i].value;
                    368: 		}
                    369: 	    }
                    370: 	} else {
                    371: 	    if (radioButton.checked) return radioButton.value;
                    372: 	}
                    373: 	return selection;
                    374:     }
                    375: 
                    376:     function pullDownSelection(selectOne) {
                    377: 	var selection="";
                    378: 	if (selectOne.length > 1) {
                    379: 	    for (var i=0; i<selectOne.length; i++) {
                    380: 		if (selectOne[i].selected) {
                    381: 		    return selectOne[i].value;
                    382: 		}
                    383: 	    }
                    384: 	} else {
1.138     albertel  385:             // only one value it must be the selected one
                    386: 	    return selectOne.value;
1.118     ng        387: 	}
                    388:     }
                    389: </script>
                    390: COMMONJSFUNCTIONS
                    391: }
                    392: 
1.44      ng        393: #--- Dumps the class list with usernames,list of sections,
                    394: #--- section, ids and fullnames for each user.
                    395: sub getclasslist {
1.449     banghart  396:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  397:     my @getsec;
1.450     banghart  398:     my @getgroup;
1.442     banghart  399:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  400:     if (!ref($getsec)) {
                    401: 	if ($getsec ne '' && $getsec ne 'all') {
                    402: 	    @getsec=($getsec);
                    403: 	}
                    404:     } else {
                    405: 	@getsec=@{$getsec};
                    406:     }
                    407:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  408:     if (!ref($getgroup)) {
                    409: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    410: 	    @getgroup=($getgroup);
                    411: 	}
                    412:     } else {
                    413: 	@getgroup=@{$getgroup};
                    414:     }
                    415:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  416: 
1.449     banghart  417:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  418:     # Bail out if we were unable to get the classlist
1.56      matthew   419:     return if (! defined($classlist));
1.449     banghart  420:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   421:     #
                    422:     my %sections;
                    423:     my %fullnames;
1.205     matthew   424:     foreach my $student (keys(%$classlist)) {
                    425:         my $end      = 
                    426:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    427:         my $start    = 
                    428:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    429:         my $id       = 
                    430:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    431:         my $section  = 
                    432:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    433:         my $fullname = 
                    434:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    435:         my $status   = 
                    436:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  437:         my $group   = 
                    438:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        439: 	# filter students according to status selected
1.442     banghart  440: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    441: 	    if (!($stu_status =~ $status)) {
1.450     banghart  442: 		delete($classlist->{$student});
1.76      ng        443: 		next;
                    444: 	    }
                    445: 	}
1.450     banghart  446: 	# filter students according to groups selected
1.453     banghart  447: 	my @stu_groups = split(/,/,$group);
1.450     banghart  448: 	if (@getgroup) {
                    449: 	    my $exclude = 1;
1.454     banghart  450: 	    foreach my $grp (@getgroup) {
                    451: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  452: 	            if ($stu_group eq $grp) {
                    453: 	                $exclude = 0;
                    454:     	            } 
1.450     banghart  455: 	        }
1.453     banghart  456:     	        if (($grp eq 'none') && !$group) {
                    457:         	        $exclude = 0;
                    458:         	}
1.450     banghart  459: 	    }
                    460: 	    if ($exclude) {
                    461: 	        delete($classlist->{$student});
                    462: 	    }
                    463: 	}
1.205     matthew   464: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  465: 	if (&canview($section)) {
1.291     albertel  466: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  467: 		$sections{$section}++;
1.450     banghart  468: 		if ($classlist->{$student}) {
                    469: 		    $fullnames{$student}=$fullname;
                    470: 		}
1.103     albertel  471: 	    } else {
1.205     matthew   472: 		delete($classlist->{$student});
1.103     albertel  473: 	    }
                    474: 	} else {
1.205     matthew   475: 	    delete($classlist->{$student});
1.103     albertel  476: 	}
1.44      ng        477:     }
                    478:     my %seen = ();
1.56      matthew   479:     my @sections = sort(keys(%sections));
                    480:     return ($classlist,\@sections,\%fullnames);
1.44      ng        481: }
                    482: 
1.103     albertel  483: sub canmodify {
                    484:     my ($sec)=@_;
                    485:     if ($perm{'mgr'}) {
                    486: 	if (!defined($perm{'mgr_section'})) {
                    487: 	    # can modify whole class
                    488: 	    return 1;
                    489: 	} else {
                    490: 	    if ($sec eq $perm{'mgr_section'}) {
                    491: 		#can modify the requested section
                    492: 		return 1;
                    493: 	    } else {
                    494: 		# can't modify the request section
                    495: 		return 0;
                    496: 	    }
                    497: 	}
                    498:     }
                    499:     #can't modify
                    500:     return 0;
                    501: }
                    502: 
                    503: sub canview {
                    504:     my ($sec)=@_;
                    505:     if ($perm{'vgr'}) {
                    506: 	if (!defined($perm{'vgr_section'})) {
                    507: 	    # can modify whole class
                    508: 	    return 1;
                    509: 	} else {
                    510: 	    if ($sec eq $perm{'vgr_section'}) {
                    511: 		#can modify the requested section
                    512: 		return 1;
                    513: 	    } else {
                    514: 		# can't modify the request section
                    515: 		return 0;
                    516: 	    }
                    517: 	}
                    518:     }
                    519:     #can't modify
                    520:     return 0;
                    521: }
                    522: 
1.44      ng        523: #--- Retrieve the grade status of a student for all the parts
                    524: sub student_gradeStatus {
1.324     albertel  525:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  526:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        527:     my %partstatus = ();
                    528:     foreach (@$partlist) {
1.128     ng        529: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        530: 	$status              = 'nothing' if ($status eq '');
                    531: 	$partstatus{$_}      = $status;
                    532: 	my $subkey           = "resource.$_.submitted_by";
                    533: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    534:     }
                    535:     return %partstatus;
                    536: }
                    537: 
1.45      ng        538: # hidden form and javascript that calls the form
                    539: # Use by verifyscript and viewgrades
                    540: # Shows a student's view of problem and submission
                    541: sub jscriptNform {
1.324     albertel  542:     my ($symb) = @_;
1.442     banghart  543:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        544:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    545: 	'    function viewOneStudent(user,domain) {'."\n".
                    546: 	'	document.onestudent.student.value = user;'."\n".
                    547: 	'	document.onestudent.userdom.value = domain;'."\n".
                    548: 	'	document.onestudent.submit();'."\n".
                    549: 	'    }'."\n".
                    550: 	'</script>'."\n";
                    551:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  552: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  553: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    554: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  555: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        556: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    557: 	'<input type="hidden" name="student" value="" />'."\n".
                    558: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    559: 	'</form>'."\n";
                    560:     return $jscript;
                    561: }
1.39      ng        562: 
1.447     foxr      563: 
                    564: 
1.315     bowersj2  565: # Given the score (as a number [0-1] and the weight) what is the final
                    566: # point value? This function will round to the nearest tenth, third,
                    567: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  568: sub compute_points {
1.315     bowersj2  569:     my ($score, $weight) = @_;
                    570:     
                    571:     my $tolerance = .00001;
                    572:     my $points = $score * $weight;
                    573: 
                    574:     # Check for nearness to 1/x.
                    575:     my $check_for_nearness = sub {
                    576:         my ($factor) = @_;
                    577:         my $num = ($points * $factor) + $tolerance;
                    578:         my $floored_num = floor($num);
1.316     albertel  579:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  580:             return $floored_num / $factor;
                    581:         }
                    582:         return $points;
                    583:     };
                    584: 
                    585:     $points = $check_for_nearness->(10);
                    586:     $points = $check_for_nearness->(3);
                    587:     $points = $check_for_nearness->(4);
                    588:     
                    589:     return $points;
                    590: }
                    591: 
1.44      ng        592: #------------------ End of general use routines --------------------
1.87      www       593: 
                    594: #
                    595: # Find most similar essay
                    596: #
                    597: 
                    598: sub most_similar {
1.426     albertel  599:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       600: 
                    601: # ignore spaces and punctuation
                    602: 
                    603:     $uessay=~s/\W+/ /gs;
                    604: 
1.282     www       605: # ignore empty submissions (occuring when only files are sent)
                    606: 
                    607:     unless ($uessay=~/\w+/) { return ''; }
                    608: 
1.87      www       609: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       610:     my $limit=0.6;
1.87      www       611:     my $sname='';
                    612:     my $sdom='';
                    613:     my $scrsid='';
                    614:     my $sessay='';
                    615: # go through all essays ...
1.426     albertel  616:     foreach my $tkey (keys(%$old_essays)) {
                    617: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       618: # ... except the same student
1.426     albertel  619:         next if (($tname eq $uname) && ($tdom eq $udom));
                    620: 	my $tessay=$old_essays->{$tkey};
                    621: 	$tessay=~s/\W+/ /gs;
1.87      www       622: # String similarity gives up if not even limit
1.426     albertel  623: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       624: # Found one
1.426     albertel  625: 	if ($tsimilar>$limit) {
                    626: 	    $limit=$tsimilar;
                    627: 	    $sname=$tname;
                    628: 	    $sdom=$tdom;
                    629: 	    $scrsid=$tcrsid;
                    630: 	    $sessay=$old_essays->{$tkey};
                    631: 	}
1.87      www       632:     }
1.88      www       633:     if ($limit>0.6) {
1.87      www       634:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    635:     } else {
                    636:        return ('','','','',0);
                    637:     }
                    638: }
                    639: 
1.44      ng        640: #-------------------------------------------------------------------
                    641: 
                    642: #------------------------------------ Receipt Verification Routines
1.45      ng        643: #
1.44      ng        644: #--- Check whether a receipt number is valid.---
                    645: sub verifyreceipt {
                    646:     my $request  = shift;
                    647: 
1.257     albertel  648:     my $courseid = $env{'request.course.id'};
1.184     www       649:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  650: 	$env{'form.receipt'};
1.44      ng        651:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  652:     my ($symb)   = &get_symb($request);
1.44      ng        653: 
1.487     albertel  654:     my $title.=
                    655: 	'<h3><span class="LC_info">'.
                    656: 	&mt('Verifying Submission Receipt [_1]',$receipt).
                    657: 	'</span></h3>'."\n".
                    658: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    659: 	'</h4>'."\n";
1.44      ng        660: 
                    661:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   662:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  663:     
                    664:     my $receiptparts=0;
1.390     albertel  665:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    666: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  667:     my $parts=['0'];
1.324     albertel  668:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.486     albertel  669:     
                    670:     my $header = 
                    671: 	&Apache::loncommon::start_data_table().
                    672: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  673: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    674: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    675: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  676:     if ($receiptparts) {
1.487     albertel  677: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  678:     }
                    679:     $header.=
                    680: 	&Apache::loncommon::end_data_table_header_row();
                    681: 
1.294     albertel  682:     foreach (sort 
                    683: 	     {
                    684: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    685: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    686: 		 }
                    687: 		 return $a cmp $b;
                    688: 	     } (keys(%$fullname))) {
1.44      ng        689: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  690: 	foreach my $part (@$parts) {
                    691: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  692: 		$contents.=
                    693: 		    &Apache::loncommon::start_data_table_row().
                    694: 		    '<td>&nbsp;'."\n".
1.177     albertel  695: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  696: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  697: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    698: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    699: 		if ($receiptparts) {
                    700: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    701: 		}
1.486     albertel  702: 		$contents.= 
                    703: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  704: 		
                    705: 		$matches++;
                    706: 	    }
1.44      ng        707: 	}
                    708:     }
                    709:     if ($matches == 0) {
1.487     albertel  710: 	$string = $title.&mt('No match found for the above receipt.');
1.44      ng        711:     } else {
1.324     albertel  712: 	$string = &jscriptNform($symb).$title.
1.487     albertel  713: 	    '<p>'.
                    714: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
                    715: 	    '</p>'.
1.486     albertel  716: 	    $header.
                    717: 	    $contents.
                    718: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        719:     }
1.324     albertel  720:     return $string.&show_grading_menu_form($symb);
1.44      ng        721: }
                    722: 
                    723: #--- This is called by a number of programs.
                    724: #--- Called from the Grading Menu - View/Grade an individual student
                    725: #--- Also called directly when one clicks on the subm button 
                    726: #    on the problem page.
1.30      ng        727: sub listStudents {
1.41      ng        728:     my ($request) = shift;
1.49      albertel  729: 
1.324     albertel  730:     my ($symb) = &get_symb($request);
1.257     albertel  731:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    732:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    733:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  734:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  735:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    736:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    737:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    738: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  739: 
1.485     albertel  740:     my $result='<h3><span class="LC_info">&nbsp;'.
                    741: 	&mt($viewgrade.' Submissions for a Student or a Group of Students')
                    742: 	.'</span></h3>';
1.118     ng        743: 
1.324     albertel  744:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  745: 
1.485     albertel  746:     my %lt = ( 'multiple' =>
                    747: 	       "Please select a student or group of students before clicking on the Next button.",
                    748: 	       'single'   =>
                    749: 	       "Please select the student before clicking on the Next button.",
                    750: 	       );
                    751:     %lt = &Apache::lonlocal::texthash(%lt);
1.45      ng        752:     $request->print(<<LISTJAVASCRIPT);
                    753: <script type="text/javascript" language="javascript">
1.110     ng        754:     function checkSelect(checkBox) {
                    755: 	var ctr=0;
                    756: 	var sense="";
                    757: 	if (checkBox.length > 1) {
                    758: 	    for (var i=0; i<checkBox.length; i++) {
                    759: 		if (checkBox[i].checked) {
                    760: 		    ctr++;
                    761: 		}
                    762: 	    }
1.485     albertel  763: 	    sense = '$lt{'multiple'}';
1.110     ng        764: 	} else {
                    765: 	    if (checkBox.checked) {
                    766: 		ctr = 1;
                    767: 	    }
1.485     albertel  768: 	    sense = '$lt{'single'}';
1.110     ng        769: 	}
                    770: 	if (ctr == 0) {
1.485     albertel  771: 	    alert(sense);
1.110     ng        772: 	    return false;
                    773: 	}
                    774: 	document.gradesub.submit();
                    775:     }
                    776: 
                    777:     function reLoadList(formname) {
1.112     ng        778: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        779: 	formname.command.value = 'submission';
                    780: 	formname.submit();
                    781:     }
1.45      ng        782: </script>
                    783: LISTJAVASCRIPT
                    784: 
1.118     ng        785:     &commonJSfunctions($request);
1.41      ng        786:     $request->print($result);
1.39      ng        787: 
1.401     albertel  788:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    789:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  790:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  791: 	"\n".$table;
                    792: 	
                    793:     $gradeTable .= 
                    794: 	'&nbsp;'.
                    795: 	&mt('<b>View Problem Text: </b>[_1]',
                    796: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                    797: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
                    798: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label>').'<br />'."\n";
                    799:     $gradeTable .= 
                    800: 	'&nbsp;'.
                    801: 	&mt('<b>View Answer: </b>[_1]',
                    802: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
                    803: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
                    804: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label>').'<br />'."\n";
                    805: 
                    806:     my $submission_options;
1.257     albertel  807:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  808: 	$submission_options.=
                    809: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  810:     }
1.442     banghart  811:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    812:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  813:     $env{'form.Status'} = $saveStatus;
1.485     albertel  814:     $submission_options.=
                    815: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
                    816: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
                    817: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
                    818: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
                    819:     $gradeTable .= 
                    820: 	'&nbsp;'.
                    821: 	&mt('<b>Submissions: </b>[_1]',$submission_options).'<br />'."\n";
                    822: 
                    823:     $gradeTable .= 
                    824:         '&nbsp;'.
                    825: 	&mt('<b>Grading Increments:</b> [_1]',
                    826: 	    '<select name="increment">'.
                    827: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
                    828: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
                    829: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
                    830: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
                    831: 	    '</select>');
                    832:     
                    833:     $gradeTable .= 
1.432     banghart  834:         &build_section_inputs().
1.45      ng        835: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  836: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    837: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    838: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    839: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  840: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        841: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    842: 
1.257     albertel  843:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart  844: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng        845:     } else {
1.485     albertel  846: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
                    847: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
1.124     ng        848:     }
1.112     ng        849: 
1.485     albertel  850:     $gradeTable.=&mt('To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    851: 	'next to the student\'s name(s). Then click on the Next button.').'<br />'."\n".
1.110     ng        852: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  853: 
                    854: # checkall buttons
                    855:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        856:     $gradeTable.='<input type="button" '."\n".
1.45      ng        857: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.485     albertel  858: 	'value="'.&mt('Next-&gt;').'" /> <br />'."\n";
1.249     albertel  859:     $gradeTable.=&check_buttons();
1.485     albertel  860:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
1.450     banghart  861:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  862:     $gradeTable.= &Apache::loncommon::start_data_table().
                    863: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        864:     my $loop = 0;
                    865:     while ($loop < 2) {
1.485     albertel  866: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    867: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel  868: 	if ($env{'form.showgrading'} eq 'yes' 
                    869: 	    && $submitonly ne 'queued'
                    870: 	    && $submitonly ne 'all') {
1.485     albertel  871: 	    foreach my $part (sort(@$partlist)) {
                    872: 		my $display_part=
                    873: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    874: 		$gradeTable.=
                    875: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        876: 	    }
1.301     albertel  877: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  878: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        879: 	}
                    880: 	$loop++;
1.126     ng        881: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        882:     }
1.474     albertel  883:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        884: 
1.45      ng        885:     my $ctr = 0;
1.294     albertel  886:     foreach my $student (sort 
                    887: 			 {
                    888: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    889: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    890: 			     }
                    891: 			     return $a cmp $b;
                    892: 			 }
                    893: 			 (keys(%$fullname))) {
1.41      ng        894: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  895: 
1.110     ng        896: 	my %status = ();
1.301     albertel  897: 
                    898: 	if ($submitonly eq 'queued') {
                    899: 	    my %queue_status = 
                    900: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    901: 							$udom,$uname);
                    902: 	    next if (!defined($queue_status{'gradingqueue'}));
                    903: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    904: 	}
                    905: 
                    906: 	if ($env{'form.showgrading'} eq 'yes' 
                    907: 	    && $submitonly ne 'queued'
                    908: 	    && $submitonly ne 'all') {
1.324     albertel  909: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  910: 	    my $submitted = 0;
1.164     albertel  911: 	    my $graded = 0;
1.248     albertel  912: 	    my $incorrect = 0;
1.110     ng        913: 	    foreach (keys(%status)) {
1.145     albertel  914: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  915: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    916: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    917: 		
1.110     ng        918: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    919: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  920: 		    $submitted = 0;
1.150     albertel  921: 		    my ($part)=split(/\./,$partid);
1.110     ng        922: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  923: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        924: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    925: 		}
1.41      ng        926: 	    }
1.248     albertel  927: 	    
1.156     albertel  928: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    929: 				     $submitonly eq 'incorrect' ||
                    930: 				     $submitonly eq 'graded'));
1.248     albertel  931: 	    next if (!$graded && ($submitonly eq 'graded'));
                    932: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        933: 	}
1.34      ng        934: 
1.45      ng        935: 	$ctr++;
1.249     albertel  936: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart  937:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel  938: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel  939: 	    if ($ctr%2 ==1) {
                    940: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                    941: 	    }
1.126     ng        942: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  943:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    944:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    945: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    946: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel  947: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng        948: 
1.257     albertel  949: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        950: 		foreach (sort keys(%status)) {
1.485     albertel  951: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                    952: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng        953: 		}
1.41      ng        954: 	    }
1.126     ng        955: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel  956: 	    if ($ctr%2 ==0) {
                    957: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                    958: 	    }
1.41      ng        959: 	}
                    960:     }
1.110     ng        961:     if ($ctr%2 ==1) {
1.126     ng        962: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel  963: 	    if ($env{'form.showgrading'} eq 'yes' 
                    964: 		&& $submitonly ne 'queued'
                    965: 		&& $submitonly ne 'all') {
1.110     ng        966: 		foreach (@$partlist) {
                    967: 		    $gradeTable.='<td>&nbsp;</td>';
                    968: 		}
1.301     albertel  969: 	    } elsif ($submitonly eq 'queued') {
                    970: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng        971: 	    }
1.474     albertel  972: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng        973:     }
                    974: 
1.474     albertel  975:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.45      ng        976: 	'<input type="button" '.
                    977: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.485     albertel  978: 	'value="'.&mt('Next-&gt;').'" /></form>'."\n";
1.45      ng        979:     if ($ctr == 0) {
1.96      albertel  980: 	my $num_students=(scalar(keys(%$fullname)));
                    981: 	if ($num_students eq 0) {
1.485     albertel  982: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel  983: 	} else {
1.171     albertel  984: 	    my $submissions='submissions';
                    985: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                    986: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel  987: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel  988: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel  989: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                    990: 		    $num_students).
                    991: 		'</span><br />';
1.96      albertel  992: 	}
1.46      ng        993:     } elsif ($ctr == 1) {
1.474     albertel  994: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng        995:     }
1.324     albertel  996:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng        997:     $request->print($gradeTable);
1.44      ng        998:     return '';
1.10      ng        999: }
                   1000: 
1.44      ng       1001: #---- Called from the listStudents routine
1.249     albertel 1002: 
                   1003: sub check_script {
                   1004:     my ($form, $type)=@_;
                   1005:     my $chkallscript='<script type="text/javascript">
                   1006:     function checkall() {
                   1007:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1008:             ele = document.forms.'.$form.'.elements[i];
                   1009:             if (ele.name == "'.$type.'") {
                   1010:             document.forms.'.$form.'.elements[i].checked=true;
                   1011:                                        }
                   1012:         }
                   1013:     }
                   1014: 
                   1015:     function checksec() {
                   1016:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1017:             ele = document.forms.'.$form.'.elements[i];
                   1018:            string = document.forms.'.$form.'.chksec.value;
                   1019:            if
                   1020:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1021:               document.forms.'.$form.'.elements[i].checked=true;
                   1022:             }
                   1023:         }
                   1024:     }
                   1025: 
                   1026: 
                   1027:     function uncheckall() {
                   1028:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1029:             ele = document.forms.'.$form.'.elements[i];
                   1030:             if (ele.name == "'.$type.'") {
                   1031:             document.forms.'.$form.'.elements[i].checked=false;
                   1032:                                        }
                   1033:         }
                   1034:     }
                   1035: 
                   1036: </script>'."\n";
                   1037:     return $chkallscript;
                   1038: }
                   1039: 
                   1040: sub check_buttons {
1.485     albertel 1041:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1042:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1043:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1044:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1045:     return $buttons;
                   1046: }
                   1047: 
1.44      ng       1048: #     Displays the submissions for one student or a group of students
1.34      ng       1049: sub processGroup {
1.41      ng       1050:     my ($request)  = shift;
                   1051:     my $ctr        = 0;
1.155     albertel 1052:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1053:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1054: 
1.396     banghart 1055:     foreach my $student (@stuchecked) {
                   1056: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1057: 	$env{'form.student'}        = $uname;
                   1058: 	$env{'form.userdom'}        = $udom;
                   1059: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1060: 	&submission($request,$ctr,$total);
                   1061: 	$ctr++;
                   1062:     }
                   1063:     return '';
1.35      ng       1064: }
1.34      ng       1065: 
1.44      ng       1066: #------------------------------------------------------------------------------------
                   1067: #
                   1068: #-------------------------- Next few routines handles grading by student, essentially
                   1069: #                           handles essay response type problem/part
                   1070: #
                   1071: #--- Javascript to handle the submission page functionality ---
                   1072: sub sub_page_js {
                   1073:     my $request = shift;
                   1074:     $request->print(<<SUBJAVASCRIPT);
                   1075: <script type="text/javascript" language="javascript">
1.71      ng       1076:     function updateRadio(formname,id,weight) {
1.125     ng       1077: 	var gradeBox = formname["GD_BOX"+id];
                   1078: 	var radioButton = formname["RADVAL"+id];
                   1079: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1080: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1081: 	gradeBox.value = pts;
                   1082: 	var resetbox = false;
                   1083: 	if (isNaN(pts) || pts < 0) {
                   1084: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1085: 	    for (var i=0; i<radioButton.length; i++) {
                   1086: 		if (radioButton[i].checked) {
                   1087: 		    gradeBox.value = i;
                   1088: 		    resetbox = true;
                   1089: 		}
                   1090: 	    }
                   1091: 	    if (!resetbox) {
                   1092: 		formtextbox.value = "";
                   1093: 	    }
                   1094: 	    return;
1.44      ng       1095: 	}
1.71      ng       1096: 
                   1097: 	if (pts > weight) {
                   1098: 	    var resp = confirm("You entered a value ("+pts+
                   1099: 			       ") greater than the weight for the part. Accept?");
                   1100: 	    if (resp == false) {
1.125     ng       1101: 		gradeBox.value = oldpts;
1.71      ng       1102: 		return;
                   1103: 	    }
1.44      ng       1104: 	}
1.13      albertel 1105: 
1.71      ng       1106: 	for (var i=0; i<radioButton.length; i++) {
                   1107: 	    radioButton[i].checked=false;
                   1108: 	    if (pts == i && pts != "") {
                   1109: 		radioButton[i].checked=true;
                   1110: 	    }
                   1111: 	}
                   1112: 	updateSelect(formname,id);
1.125     ng       1113: 	formname["stores"+id].value = "0";
1.41      ng       1114:     }
1.5       albertel 1115: 
1.72      ng       1116:     function writeBox(formname,id,pts) {
1.125     ng       1117: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1118: 	if (checkSolved(formname,id) == 'update') {
                   1119: 	    gradeBox.value = pts;
                   1120: 	} else {
1.125     ng       1121: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1122: 	    gradeBox.value = oldpts;
1.125     ng       1123: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1124: 	    for (var i=0; i<radioButton.length; i++) {
                   1125: 		radioButton[i].checked=false;
1.72      ng       1126: 		if (i == oldpts) {
1.71      ng       1127: 		    radioButton[i].checked=true;
                   1128: 		}
                   1129: 	    }
1.41      ng       1130: 	}
1.125     ng       1131: 	formname["stores"+id].value = "0";
1.71      ng       1132: 	updateSelect(formname,id);
                   1133: 	return;
1.41      ng       1134:     }
1.44      ng       1135: 
1.71      ng       1136:     function clearRadBox(formname,id) {
                   1137: 	if (checkSolved(formname,id) == 'noupdate') {
                   1138: 	    updateSelect(formname,id);
                   1139: 	    return;
                   1140: 	}
1.125     ng       1141: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1142: 	for (var i=0; i<gradeSelect.length; i++) {
                   1143: 	    if (gradeSelect[i].selected) {
                   1144: 		var selectx=i;
                   1145: 	    }
                   1146: 	}
1.125     ng       1147: 	var stores = formname["stores"+id];
1.71      ng       1148: 	if (selectx == stores.value) { return };
1.125     ng       1149: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1150: 	gradeBox.value = "";
1.125     ng       1151: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1152: 	for (var i=0; i<radioButton.length; i++) {
                   1153: 	    radioButton[i].checked=false;
                   1154: 	}
                   1155: 	stores.value = selectx;
                   1156:     }
1.5       albertel 1157: 
1.71      ng       1158:     function checkSolved(formname,id) {
1.125     ng       1159: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1160: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1161: 	    if (!reply) {return "noupdate";}
1.120     ng       1162: 	    formname.overRideScore.value = 'yes';
1.41      ng       1163: 	}
1.71      ng       1164: 	return "update";
1.13      albertel 1165:     }
1.71      ng       1166: 
                   1167:     function updateSelect(formname,id) {
1.125     ng       1168: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1169: 	return;
1.41      ng       1170:     }
1.33      ng       1171: 
1.121     ng       1172: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1173:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1174: 	formname.gradeOpt.value = val;
1.71      ng       1175: 	if (val == "Save & Next") {
                   1176: 	    for (i=0;i<=total;i++) {
                   1177: 		for (j=0;j<parttot;j++) {
1.125     ng       1178: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1179: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1180: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1181: 			if (points == "") {
1.125     ng       1182: 			    var name = formname["name"+i].value;
1.129     ng       1183: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1184: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1185: 					       ", part "+partid+". Continue?");
1.71      ng       1186: 			    if (resp == false) {
1.125     ng       1187: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1188: 				return false;
                   1189: 			    }
                   1190: 			}
                   1191: 		    }
                   1192: 		    
                   1193: 		}
                   1194: 	    }
                   1195: 	    
                   1196: 	}
1.121     ng       1197: 	if (val == "Grade Student") {
                   1198: 	    formname.showgrading.value = "yes";
                   1199: 	    if (formname.Status.value == "") {
                   1200: 		formname.Status.value = "Active";
                   1201: 	    }
                   1202: 	    formname.studentNo.value = total;
                   1203: 	}
1.120     ng       1204: 	formname.submit();
                   1205:     }
                   1206: 
1.71      ng       1207: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1208:     function checkSubmitPage(formname,total) {
                   1209: 	noscore = new Array(100);
                   1210: 	var ptr = 0;
                   1211: 	for (i=1;i<total;i++) {
1.125     ng       1212: 	    var partid = formname["q_"+i].value;
1.127     ng       1213: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1214: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1215: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1216: 		if (points == "" && status != "correct_by_student") {
                   1217: 		    noscore[ptr] = i;
                   1218: 		    ptr++;
                   1219: 		}
                   1220: 	    }
                   1221: 	}
                   1222: 	if (ptr != 0) {
                   1223: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1224: 	    var prolist = "";
                   1225: 	    if (ptr == 1) {
                   1226: 		prolist = noscore[0];
                   1227: 	    } else {
                   1228: 		var i = 0;
                   1229: 		while (i < ptr-1) {
                   1230: 		    prolist += noscore[i]+", ";
                   1231: 		    i++;
                   1232: 		}
                   1233: 		prolist += "and "+noscore[i];
                   1234: 	    }
                   1235: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1236: 	    if (resp == false) {
                   1237: 		return false;
                   1238: 	    }
                   1239: 	}
1.45      ng       1240: 
1.71      ng       1241: 	formname.submit();
                   1242:     }
                   1243: </script>
                   1244: SUBJAVASCRIPT
                   1245: }
1.45      ng       1246: 
1.71      ng       1247: #--- javascript for essay type problem --
                   1248: sub sub_page_kw_js {
                   1249:     my $request = shift;
1.80      ng       1250:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1251:     &commonJSfunctions($request);
1.350     albertel 1252: 
1.351     albertel 1253:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1254:     <script text="text/javascript">
                   1255:     function checkInput() {
                   1256:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1257:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1258:       var usrctr = document.msgcenter.usrctr.value;
                   1259:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1260:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1261: 
                   1262:       var msgchk = "";
                   1263:       if (document.msgcenter.subchk.checked) {
                   1264:          msgchk = "msgsub,";
                   1265:       }
                   1266:       var includemsg = 0;
                   1267:       for (var i=1; i<=nmsg; i++) {
                   1268:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1269:           var frmmsg = document.msgcenter["msg"+i];
                   1270:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1271:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1272:           showflg.value = "1";
                   1273:           var chkbox = document.msgcenter["msgn"+i];
                   1274:           if (chkbox.checked) {
                   1275:              msgchk += "savemsg"+i+",";
                   1276:              includemsg = 1;
                   1277:           }
                   1278:       }
                   1279:       if (document.msgcenter.newmsgchk.checked) {
                   1280:          msgchk += "newmsg"+usrctr;
                   1281:          includemsg = 1;
                   1282:       }
                   1283:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1284:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1285:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1286:       includemsg.value = msgchk;
                   1287: 
                   1288:       self.close()
                   1289: 
                   1290:     }
                   1291:     </script>
                   1292: INNERJS
                   1293: 
1.351     albertel 1294:     my $inner_js_highlight_central=<<INNERJS;
                   1295:  <script type="text/javascript">
                   1296:     function updateChoice(flag) {
                   1297:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1298:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1299:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1300:       opener.document.SCORE.refresh.value = "on";
                   1301:       if (opener.document.SCORE.keywords.value!=""){
                   1302:          opener.document.SCORE.submit();
                   1303:       }
                   1304:       self.close()
                   1305:     }
                   1306: </script>
                   1307: INNERJS
                   1308: 
                   1309:     my $start_page_msg_central = 
                   1310:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1311: 				       {'js_ready'  => 1,
                   1312: 					'only_body' => 1,
                   1313: 					'bgcolor'   =>'#FFFFFF',});
                   1314:     my $end_page_msg_central = 
                   1315: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1316: 
                   1317: 
                   1318:     my $start_page_highlight_central = 
                   1319:         &Apache::loncommon::start_page('Highlight Central',
                   1320: 				       $inner_js_highlight_central,
1.350     albertel 1321: 				       {'js_ready'  => 1,
                   1322: 					'only_body' => 1,
                   1323: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1324:     my $end_page_highlight_central = 
1.350     albertel 1325: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1326: 
1.219     www      1327:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1328:     $docopen=~s/^document\.//;
1.71      ng       1329:     $request->print(<<SUBJAVASCRIPT);
                   1330: <script type="text/javascript" language="javascript">
1.45      ng       1331: 
1.44      ng       1332: //===================== Show list of keywords ====================
1.122     ng       1333:   function keywords(formname) {
                   1334:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1335:     if (nret==null) return;
1.122     ng       1336:     formname.keywords.value = nret;
1.44      ng       1337: 
1.122     ng       1338:     if (formname.keywords.value != "") {
1.128     ng       1339: 	formname.refresh.value = "on";
1.122     ng       1340: 	formname.submit();
1.44      ng       1341:     }
                   1342:     return;
                   1343:   }
                   1344: 
                   1345: //===================== Script to view submitted by ==================
                   1346:   function viewSubmitter(submitter) {
                   1347:     document.SCORE.refresh.value = "on";
                   1348:     document.SCORE.NCT.value = "1";
                   1349:     document.SCORE.unamedom0.value = submitter;
                   1350:     document.SCORE.submit();
                   1351:     return;
                   1352:   }
                   1353: 
                   1354: //===================== Script to add keyword(s) ==================
                   1355:   function getSel() {
                   1356:     if (document.getSelection) txt = document.getSelection();
                   1357:     else if (document.selection) txt = document.selection.createRange().text;
                   1358:     else return;
                   1359:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1360:     if (cleantxt=="") {
1.46      ng       1361: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1362: 	return;
                   1363:     }
                   1364:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1365:     if (nret==null) return;
1.127     ng       1366:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1367:     if (document.SCORE.keywords.value != "") {
1.127     ng       1368: 	document.SCORE.refresh.value = "on";
1.44      ng       1369: 	document.SCORE.submit();
                   1370:     }
                   1371:     return;
                   1372:   }
                   1373: 
                   1374: //====================== Script for composing message ==============
1.80      ng       1375:    // preload images
                   1376:    img1 = new Image();
                   1377:    img1.src = "$iconpath/mailbkgrd.gif";
                   1378:    img2 = new Image();
                   1379:    img2.src = "$iconpath/mailto.gif";
                   1380: 
1.44      ng       1381:   function msgCenter(msgform,usrctr,fullname) {
                   1382:     var Nmsg  = msgform.savemsgN.value;
                   1383:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1384:     var subject = msgform.msgsub.value;
1.127     ng       1385:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1386:     re = /msgsub/;
                   1387:     var shwsel = "";
                   1388:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1389:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1390:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1391:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1392: 	var testmsg = "savemsg"+i+",";
                   1393: 	re = new RegExp(testmsg,"g");
1.44      ng       1394: 	shwsel = "";
                   1395: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1396: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1397: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1398: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1399: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1400:     }
1.125     ng       1401:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1402:     shwsel = "";
                   1403:     re = /newmsg/;
                   1404:     if (re.test(msgchk)) { shwsel = "checked" }
                   1405:     newMsg(newmsg,shwsel);
                   1406:     msgTail(); 
                   1407:     return;
                   1408:   }
                   1409: 
1.123     ng       1410:   function checkEntities(strx) {
                   1411:     if (strx.length == 0) return strx;
                   1412:     var orgStr = ["&", "<", ">", '"']; 
                   1413:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1414:     var counter = 0;
                   1415:     while (counter < 4) {
                   1416: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1417: 	counter++;
                   1418:     }
                   1419:     return strx;
                   1420:   }
                   1421: 
                   1422:   function strReplace(strx, orgStr, newStr) {
                   1423:     return strx.split(orgStr).join(newStr);
                   1424:   }
                   1425: 
1.44      ng       1426:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1427:     var height = 70*Nmsg+250;
1.44      ng       1428:     var scrollbar = "no";
                   1429:     if (height > 600) {
                   1430: 	height = 600;
                   1431: 	scrollbar = "yes";
                   1432:     }
1.118     ng       1433:     var xpos = (screen.width-600)/2;
                   1434:     xpos = (xpos < 0) ? '0' : xpos;
                   1435:     var ypos = (screen.height-height)/2-30;
                   1436:     ypos = (ypos < 0) ? '0' : ypos;
                   1437: 
1.206     albertel 1438:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1439:     pWin.focus();
                   1440:     pDoc = pWin.document;
1.219     www      1441:     pDoc.$docopen;
1.351     albertel 1442:     pDoc.write('$start_page_msg_central');
1.76      ng       1443: 
                   1444:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1445:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1446:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1447: 
                   1448:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1449:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1450:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1451: }
                   1452:     function displaySubject(msg,shwsel) {
1.76      ng       1453:     pDoc = pWin.document;
                   1454:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1455:     pDoc.write("<td>Subject<\\/td>");
                   1456:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1457:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1458: }
                   1459: 
1.72      ng       1460:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1461:     pDoc = pWin.document;
                   1462:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1463:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1464:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1465:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1466: }
                   1467: 
                   1468:   function newMsg(newmsg,shwsel) {
1.76      ng       1469:     pDoc = pWin.document;
                   1470:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1471:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1472:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1473:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1474: }
                   1475: 
                   1476:   function msgTail() {
1.76      ng       1477:     pDoc = pWin.document;
1.465     albertel 1478:     pDoc.write("<\\/table>");
                   1479:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1480:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1481:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1482:     pDoc.write("<\\/form>");
1.351     albertel 1483:     pDoc.write('$end_page_msg_central');
1.128     ng       1484:     pDoc.close();
1.44      ng       1485: }
                   1486: 
                   1487: //====================== Script for keyword highlight options ==============
                   1488:   function kwhighlight() {
                   1489:     var kwclr    = document.SCORE.kwclr.value;
                   1490:     var kwsize   = document.SCORE.kwsize.value;
                   1491:     var kwstyle  = document.SCORE.kwstyle.value;
                   1492:     var redsel = "";
                   1493:     var grnsel = "";
                   1494:     var blusel = "";
                   1495:     if (kwclr=="red")   {var redsel="checked"};
                   1496:     if (kwclr=="green") {var grnsel="checked"};
                   1497:     if (kwclr=="blue")  {var blusel="checked"};
                   1498:     var sznsel = "";
                   1499:     var sz1sel = "";
                   1500:     var sz2sel = "";
                   1501:     if (kwsize=="0")  {var sznsel="checked"};
                   1502:     if (kwsize=="+1") {var sz1sel="checked"};
                   1503:     if (kwsize=="+2") {var sz2sel="checked"};
                   1504:     var synsel = "";
                   1505:     var syisel = "";
                   1506:     var sybsel = "";
                   1507:     if (kwstyle=="")    {var synsel="checked"};
                   1508:     if (kwstyle=="<i>") {var syisel="checked"};
                   1509:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1510:     highlightCentral();
                   1511:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1512:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1513:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1514:     highlightend();
                   1515:     return;
                   1516:   }
                   1517: 
                   1518:   function highlightCentral() {
1.76      ng       1519: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1520:     var xpos = (screen.width-400)/2;
                   1521:     xpos = (xpos < 0) ? '0' : xpos;
                   1522:     var ypos = (screen.height-330)/2-30;
                   1523:     ypos = (ypos < 0) ? '0' : ypos;
                   1524: 
1.206     albertel 1525:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1526:     hwdWin.focus();
                   1527:     var hDoc = hwdWin.document;
1.219     www      1528:     hDoc.$docopen;
1.351     albertel 1529:     hDoc.write('$start_page_highlight_central');
1.76      ng       1530:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1531:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1532: 
                   1533:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1534:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1535:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1536:   }
                   1537: 
                   1538:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1539:     var hDoc = hwdWin.document;
                   1540:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1541:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1542:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1543:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1544:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1545:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1546:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1547:     hDoc.write("<\\/tr>");
1.44      ng       1548:   }
                   1549: 
                   1550:   function highlightend() { 
1.76      ng       1551:     var hDoc = hwdWin.document;
1.465     albertel 1552:     hDoc.write("<\\/table>");
                   1553:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1554:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1555:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1556:     hDoc.write("<\\/form>");
1.351     albertel 1557:     hDoc.write('$end_page_highlight_central');
1.128     ng       1558:     hDoc.close();
1.44      ng       1559:   }
                   1560: 
                   1561: </script>
                   1562: SUBJAVASCRIPT
                   1563: }
                   1564: 
1.349     albertel 1565: sub get_increment {
1.348     bowersj2 1566:     my $increment = $env{'form.increment'};
                   1567:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1568:         $increment != .1) {
                   1569:         $increment = 1;
                   1570:     }
                   1571:     return $increment;
                   1572: }
                   1573: 
1.71      ng       1574: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1575: sub gradeBox {
1.322     albertel 1576:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1577:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1578: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1579:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1580:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1581:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1582:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1583:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1584: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1585:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1586:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1587:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1588: 				       [$partid]);
                   1589:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1590:     if ($last_resets{$partid}) {
                   1591:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1592:     }
1.485     albertel 1593:     $result.='<table border="0"><tr>';
1.71      ng       1594:     my $ctr = 0;
1.348     bowersj2 1595:     my $thisweight = 0;
1.349     albertel 1596:     my $increment = &get_increment();
1.485     albertel 1597: 
                   1598:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1599:     while ($thisweight<=$wgt) {
1.485     albertel 1600: 	$radio.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1601: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1602: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1603: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1604: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1605:         $thisweight += $increment;
1.71      ng       1606: 	$ctr++;
                   1607:     }
1.485     albertel 1608:     $radio.='</tr></table>';
                   1609: 
                   1610:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1611: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1612: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1613: 	$wgt.')" /></td>'."\n";
1.485     albertel 1614:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1615: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1616: 	' </td><td>'."\n";
1.485     albertel 1617:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.71      ng       1618: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1619:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1620: 	$line.='<option></option>'.
                   1621: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1622:     } else {
1.485     albertel 1623: 	$line.='<option selected="selected"></option>'.
                   1624: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1625:     }
1.485     albertel 1626:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1627: 
                   1628: 
                   1629:     $result .= 
                   1630: 	&mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line);
                   1631: 
                   1632:     
                   1633:     $result.='</tr></table>'."\n";
1.71      ng       1634:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1635: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1636: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1637: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1638:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1639:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1640:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1641:         $aggtries.'" />'."\n";
1.323     banghart 1642:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1643:     return $result;
                   1644: }
1.322     albertel 1645: 
                   1646: sub handback_box {
1.323     banghart 1647:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1648:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1649:     my (@respids);
1.375     albertel 1650:      my @part_response_id = &flatten_responseType($responseType);
                   1651:     foreach my $part_response_id (@part_response_id) {
                   1652:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1653:         if ($part eq $partid) {
1.375     albertel 1654:             push(@respids,$resp);
1.323     banghart 1655:         }
                   1656:     }
1.318     banghart 1657:     my $result;
1.323     banghart 1658:     foreach my $respid (@respids) {
1.322     albertel 1659: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1660: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1661: 	next if (!@$files);
                   1662: 	my $file_counter = 1;
1.313     banghart 1663: 	foreach my $file (@$files) {
1.368     banghart 1664: 	    if ($file =~ /\/portfolio\//) {
                   1665:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1666:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1667:     	        $file_disp = "$name.$ext";
                   1668:     	        $file = $file_path.$file_disp;
                   1669:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1670:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1671:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1672:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1673:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1674:     	        $file_counter++;
                   1675: 	    }
1.322     albertel 1676: 	}
1.313     banghart 1677:     }
1.318     banghart 1678:     return $result;    
1.71      ng       1679: }
1.44      ng       1680: 
1.58      albertel 1681: sub show_problem {
1.382     albertel 1682:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1683:     my $rendered;
1.382     albertel 1684:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1685:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1686:     if ($mode eq 'both' or $mode eq 'text') {
                   1687: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1688: 						       $env{'request.course.id'},
                   1689: 						       undef,\%form);
1.144     albertel 1690:     }
1.58      albertel 1691:     if ($removeform) {
                   1692: 	$rendered=~s|<form(.*?)>||g;
                   1693: 	$rendered=~s|</form>||g;
1.374     albertel 1694: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1695:     }
1.144     albertel 1696:     my $companswer;
                   1697:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1698: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1699: 	$companswer=
                   1700: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1701: 						    $env{'request.course.id'},
                   1702: 						    %form);
1.144     albertel 1703:     }
1.58      albertel 1704:     if ($removeform) {
                   1705: 	$companswer=~s|<form(.*?)>||g;
                   1706: 	$companswer=~s|</form>||g;
1.144     albertel 1707: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1708:     }
1.468     albertel 1709:     $rendered=
                   1710: 	'<div class="LC_grade_show_problem_header">'.
                   1711: 	&mt('View of the problem').
                   1712: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1713: 	$rendered.
                   1714: 	'</div>';
                   1715:     $companswer=
                   1716: 	'<div class="LC_grade_show_problem_header">'.
                   1717: 	&mt('Correct answer').
                   1718: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1719: 	$companswer.
                   1720: 	'</div>';
                   1721:     my $result;
1.144     albertel 1722:     if ($mode eq 'both') {
1.468     albertel 1723: 	$result=$rendered.$companswer;
1.144     albertel 1724:     } elsif ($mode eq 'text') {
1.468     albertel 1725: 	$result=$rendered;
1.144     albertel 1726:     } elsif ($mode eq 'answer') {
1.468     albertel 1727: 	$result=$companswer;
1.144     albertel 1728:     }
1.468     albertel 1729:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1.71      ng       1730:     return $result;
1.58      albertel 1731: }
1.397     albertel 1732: 
1.396     banghart 1733: sub files_exist {
                   1734:     my ($r, $symb) = @_;
                   1735:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1736: 
1.396     banghart 1737:     foreach my $student (@students) {
                   1738:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1739:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1740: 					      $udom,$uname);
1.396     banghart 1741:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1742:         foreach my $submission (@$string) {
                   1743:             my ($partid,$respid) =
                   1744: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1745:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1746: 					   \%record);
                   1747:             return 1 if (@$files);
1.396     banghart 1748:         }
                   1749:     }
1.397     albertel 1750:     return 0;
1.396     banghart 1751: }
1.397     albertel 1752: 
1.394     banghart 1753: sub download_all_link {
                   1754:     my ($r,$symb) = @_;
1.395     albertel 1755:     my $all_students = 
                   1756: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1757: 
                   1758:     my $parts =
                   1759: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1760: 
1.394     banghart 1761:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1762:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1763:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1764:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1765:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1766: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1767:     return
                   1768: }
1.395     albertel 1769: 
1.432     banghart 1770: sub build_section_inputs {
                   1771:     my $section_inputs;
                   1772:     if ($env{'form.section'} eq '') {
                   1773:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1774:     } else {
                   1775:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1776:         foreach my $section (@sections) {
1.432     banghart 1777:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1778:         }
                   1779:     }
                   1780:     return $section_inputs;
                   1781: }
                   1782: 
1.44      ng       1783: # --------------------------- show submissions of a student, option to grade 
                   1784: sub submission {
                   1785:     my ($request,$counter,$total) = @_;
1.257     albertel 1786:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1787:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1788:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1789:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1790:     my $symb = &get_symb($request); 
                   1791:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1792: 
                   1793:     if (!&canview($usec)) {
1.398     albertel 1794: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1795: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1796: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1797: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1798: 	return;
                   1799:     }
                   1800: 
1.257     albertel 1801:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1802:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1803:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1804:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1805:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1806: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1807: 	'/check.gif" height="16" border="0" />';
1.41      ng       1808: 
1.426     albertel 1809:     my %old_essays;
1.41      ng       1810:     # header info
                   1811:     if ($counter == 0) {
                   1812: 	&sub_page_js($request);
1.257     albertel 1813: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1814: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1815: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1816: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1817: 	    &download_all_link($request, $symb);
                   1818: 	}
1.485     albertel 1819: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   1820: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       1821: 
1.44      ng       1822: 	# option to display problem, only once else it cause problems 
                   1823:         # with the form later since the problem has a form.
1.257     albertel 1824: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1825: 	    my $mode;
1.257     albertel 1826: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1827: 		$mode='both';
1.257     albertel 1828: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1829: 		$mode='text';
1.257     albertel 1830: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1831: 		$mode='answer';
                   1832: 	    }
1.329     albertel 1833: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1834: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1835: 	}
1.441     www      1836: 
1.44      ng       1837: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1838:         # if this subroutine has been called once.
1.41      ng       1839: 	my %keyhash = ();
1.257     albertel 1840: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1841: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1842: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1843: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1844: 
1.257     albertel 1845: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1846: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1847: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1848: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1849: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1850: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1851: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1852: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1853: 	}
1.257     albertel 1854: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1855: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1856: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1857: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1858: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1859: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1860: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1861: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1862: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1863: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1864: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1865: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1866: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1867: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1868: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1869: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1870: 			&build_section_inputs().
1.326     albertel 1871: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1872: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1873: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1874: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1875: 	if ($env{'form.handgrade'} eq 'yes') {
                   1876: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1877: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1878: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1879: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1880: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1881: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1882: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1883: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1884: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1885: 	    }
1.123     ng       1886: 	}
1.41      ng       1887: 	
                   1888: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1889: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1890: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1891: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1892: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1893: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1894: 		'" />'."\n".
                   1895: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1896: 	    $cts++;
                   1897: 	}
                   1898: 	$request->print($prnmsg);
1.32      ng       1899: 
1.257     albertel 1900: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1901: #
                   1902: # Print out the keyword options line
                   1903: #
1.41      ng       1904: 	    $request->print(<<KEYWORDS);
1.38      ng       1905: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1906: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1907: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1908:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1909: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1910: KEYWORDS
1.88      www      1911: #
                   1912: # Load the other essays for similarity check
                   1913: #
1.324     albertel 1914:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1915: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1916: 	    $apath=&escape($apath);
1.88      www      1917: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1918: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1919:         }
                   1920:     }
1.44      ng       1921: 
1.441     www      1922: # This is where output for one specific student would start
1.468     albertel 1923:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1.441     www      1924:     $request->print("\n\n".
1.468     albertel 1925:                     '<div class="LC_grade_show_user '.$add_class.'">'.
                   1926: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
                   1927: 		    '<div class="LC_grade_show_user_body">'."\n");
1.441     www      1928: 
1.257     albertel 1929:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 1930: 	my $mode;
1.257     albertel 1931: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1932: 	    $mode='both';
1.257     albertel 1933: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1934: 	    $mode='text';
1.257     albertel 1935: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1936: 	    $mode='answer';
                   1937: 	}
1.329     albertel 1938: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 1939: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 1940:     }
1.144     albertel 1941: 
1.257     albertel 1942:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1943:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1944: 
1.44      ng       1945:     # Display student info
1.41      ng       1946:     $request->print(($counter == 0 ? '' : '<br />'));
1.468     albertel 1947:     my $result='<div class="LC_grade_submissions">';
                   1948:     
                   1949:     $result.='<div class="LC_grade_submissions_header">';
                   1950:     $result.= &mt('Submissions');
1.45      ng       1951:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1952: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 1953:     if ($env{'form.handgrade'} eq 'no') {
                   1954: 	$result.='<span class="LC_grade_check_note">'.
                   1955: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
                   1956: 
                   1957:     }
                   1958: 
                   1959: 
1.41      ng       1960: 
1.118     ng       1961:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 1962:     my $fullname;
                   1963:     my $col_fullnames = [];
1.257     albertel 1964:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 1965: 	(my $sub_result,$fullname,$col_fullnames)=
                   1966: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   1967: 				 $counter);
                   1968: 	$result.=$sub_result;
1.41      ng       1969:     }
1.44      ng       1970:     $request->print($result."\n");
1.468     albertel 1971:     $request->print('</div>'."\n");
1.44      ng       1972:     # print student answer/submission
                   1973:     # Options are (1) Handgaded submission only
                   1974:     #             (2) Last submission, includes submission that is not handgraded 
                   1975:     #                  (for multi-response type part)
                   1976:     #             (3) Last submission plus the parts info
                   1977:     #             (4) The whole record for this student
1.257     albertel 1978:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 1979: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 1980: 	
                   1981: 	my $lastsubonly;
                   1982: 
1.151     albertel 1983: 	if ($$timestamp eq '') {
1.468     albertel 1984: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.151     albertel 1985: 	} else {
1.468     albertel 1986: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
                   1987: 
1.151     albertel 1988: 	    my %seenparts;
1.375     albertel 1989: 	    my @part_response_id = &flatten_responseType($responseType);
                   1990: 	    foreach my $part (@part_response_id) {
1.393     albertel 1991: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   1992: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   1993: 
1.375     albertel 1994: 		my ($partid,$respid) = @{ $part };
1.324     albertel 1995: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 1996: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 1997: 		    if (exists($seenparts{$partid})) { next; }
                   1998: 		    $seenparts{$partid}=1;
1.207     albertel 1999: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2000: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2001: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2002: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2003: 			'\');" target="_self">'.
1.257     albertel 2004: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2005: 		    $request->print($submitby);
                   2006: 		    next;
                   2007: 		}
                   2008: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2009: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.468     albertel 2010: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
1.398     albertel 2011: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2012: 			' )</span>&nbsp; &nbsp;'.
1.468     albertel 2013: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
1.151     albertel 2014: 		    next;
                   2015: 		}
1.468     albertel 2016: 		foreach my $submission (@$string) {
                   2017: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2018: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.468     albertel 2019: 		    my ($ressub,$subval) = split(/:/,$submission,2);
1.151     albertel 2020: 		    # Similarity check
                   2021: 		    my $similar='';
1.257     albertel 2022: 		    if($env{'form.checkPlag'}){
1.151     albertel 2023: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2024: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2025: 			if ($osim) {
                   2026: 			    $osim=int($osim*100.0);
1.426     albertel 2027: 			    my %old_course_desc = 
                   2028: 				&Apache::lonnet::coursedescription($ocrsid,
                   2029: 								   {'one_time' => 1});
                   2030: 
                   2031: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2032: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2033: 				    $osim,
                   2034: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2035: 				    $oname,$odom,
1.426     albertel 2036: 				    $old_course_desc{'description'},
1.427     albertel 2037: 				    $old_course_desc{'num'},
1.426     albertel 2038: 				    $old_course_desc{'domain'}).
1.398     albertel 2039: 				'</span></h3><blockquote><i>'.
1.151     albertel 2040: 				&keywords_highlight($oessay).
                   2041: 				'</i></blockquote><hr />';
                   2042: 			}
1.150     albertel 2043: 		    }
1.151     albertel 2044: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2045: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2046: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2047: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2048: 			my $display_part=&get_display_part($partid,$symb);
1.468     albertel 2049: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
1.403     albertel 2050: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2051: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2052: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2053: 			if (@$files) {
1.468     albertel 2054: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
1.303     banghart 2055: 			    my $file_counter = 0;
1.313     banghart 2056: 			    foreach my $file (@$files) {
1.468     albertel 2057: 			        $file_counter++;
1.232     albertel 2058: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2059: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2060: 			    }
1.236     albertel 2061: 			    $lastsubonly.='<br />';
1.41      ng       2062: 			}
1.468     albertel 2063: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
1.151     albertel 2064: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2065: 					 $respid,\%record,$order);
                   2066: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2067: 			$lastsubonly.='</div>';
1.41      ng       2068: 		    }
                   2069: 		}
                   2070: 	    }
1.468     albertel 2071: 	    $lastsubonly.='</div>'."\n";
1.151     albertel 2072: 	}
                   2073: 	$request->print($lastsubonly);
1.468     albertel 2074:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2075: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2076: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2077:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2078: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2079: 								 $env{'request.course.id'},
1.44      ng       2080: 								 $last,'.submission',
                   2081: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2082:     }
1.120     ng       2083: 
1.121     ng       2084:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2085: 	.$udom.'" />'."\n");
1.44      ng       2086:     # return if view submission with no grading option
1.257     albertel 2087:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2088: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2089: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2090: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2091: 	$toGrade.='</div>'."\n";
1.257     albertel 2092: 	if (($env{'form.command'} eq 'submission') || 
                   2093: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2094: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2095: 	}
1.180     albertel 2096: 	$request->print($toGrade);
1.41      ng       2097: 	return;
1.180     albertel 2098:     } else {
1.468     albertel 2099: 	$request->print('</div>'."\n");
1.41      ng       2100:     }
1.33      ng       2101: 
1.121     ng       2102:     # essay grading message center
1.257     albertel 2103:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2104: 	my $result='<div class="LC_grade_message_center">';
                   2105:     
                   2106: 	$result.='<div class="LC_grade_message_center_header">'.
                   2107: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2108: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2109: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2110: 	if (scalar(@$col_fullnames) > 0) {
                   2111: 	    my $lastone = pop(@$col_fullnames);
                   2112: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2113: 	}
                   2114: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2115: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2116: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2117: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2118: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2119: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2120: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2121: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2122: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2123: 	    '<br />&nbsp;('.
1.468     albertel 2124: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2125: 	$result.='</div></div>';
1.121     ng       2126: 	$request->print($result);
1.118     ng       2127:     }
1.41      ng       2128: 
                   2129:     my %seen = ();
                   2130:     my @partlist;
1.129     ng       2131:     my @gradePartRespid;
1.375     albertel 2132:     my @part_response_id = &flatten_responseType($responseType);
1.468     albertel 2133:     $request->print('<div class="LC_grade_assign">'.
                   2134: 		    
                   2135: 		    '<div class="LC_grade_assign_header">'.
                   2136: 		    &mt('Assign Grades').'</div>'.
                   2137: 		    '<div class="LC_grade_assign_body">');
1.375     albertel 2138:     foreach my $part_response_id (@part_response_id) {
                   2139:     	my ($partid,$respid) = @{ $part_response_id };
                   2140: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2141: 	next if ($seen{$partid} > 0);
1.41      ng       2142: 	$seen{$partid}++;
1.393     albertel 2143: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2144: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2145: 	push @partlist,$partid;
1.129     ng       2146: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2147: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2148:     }
1.468     albertel 2149:     $request->print('</div></div>');
                   2150: 
                   2151:     $request->print('<div class="LC_grade_info_links">');
                   2152:     if ($perm{'vgr'}) {
                   2153: 	$request->print(
                   2154: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2155: 						   $uname,$udom,'check'));
                   2156:     }
                   2157:     if ($perm{'opa'}) {
                   2158: 	$request->print(
                   2159: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2160: 					 $uname,$udom,$symb,'check'));
                   2161:     }
                   2162:     $request->print('</div>');
                   2163: 
1.45      ng       2164:     $result='<input type="hidden" name="partlist'.$counter.
                   2165: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2166:     $result.='<input type="hidden" name="gradePartRespid'.
                   2167: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2168:     my $ctr = 0;
                   2169:     while ($ctr < scalar(@partlist)) {
                   2170: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2171: 	    $partlist[$ctr].'" />'."\n";
                   2172: 	$ctr++;
                   2173:     }
1.468     albertel 2174:     $request->print($result.''."\n");
1.41      ng       2175: 
1.441     www      2176: # Done with printing info for one student
                   2177: 
1.468     albertel 2178:     $request->print('</div>');#LC_grade_show_user_body
                   2179:     $request->print('</div>');#LC_grade_show_user
1.441     www      2180: 
                   2181: 
1.41      ng       2182:     # print end of form
                   2183:     if ($counter == $total) {
1.297     www      2184: 	my $endform='<table border="0"><tr><td>'."\n";
1.485     albertel 2185: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.119     ng       2186: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2187: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2188: 	my $ntstu ='<select name="NTSTU">'.
                   2189: 	    '<option>1</option><option>2</option>'.
                   2190: 	    '<option>3</option><option>5</option>'.
                   2191: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2192: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2193: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.485     albertel 2194: 	$endform.=&mt('[_1]student(s)',$ntstu);
                   2195: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.417     albertel 2196: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2197: 	    '<input type="button" value="'.&mt('Next').'" '.
1.417     albertel 2198: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.485     albertel 2199: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
1.349     albertel 2200:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2201:             "' name='increment' />";
1.485     albertel 2202: 	$endform.='</td></tr></table></form>';
1.324     albertel 2203: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2204: 	$request->print($endform);
                   2205:     }
                   2206:     return '';
1.38      ng       2207: }
                   2208: 
1.464     albertel 2209: sub check_collaborators {
                   2210:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2211:     my ($result,@col_fullnames);
                   2212:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2213:     foreach my $part (keys(%$handgrade)) {
                   2214: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2215: 					'.maxcollaborators',
                   2216: 					$symb,$udom,$uname);
                   2217: 	next if ($ncol <= 0);
                   2218: 	$part =~ s/\_/\./g;
                   2219: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2220: 	my (@good_collaborators, @bad_collaborators);
                   2221: 	foreach my $possible_collaborator
                   2222: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2223: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2224: 	    next if ($possible_collaborator eq '');
                   2225: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2226: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2227: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2228: 	    # Doing this grep allows 'fuzzy' specification
                   2229: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2230: 			       keys(%$classlist));
                   2231: 	    if (! scalar(@matches)) {
                   2232: 		push(@bad_collaborators, $possible_collaborator);
                   2233: 	    } else {
                   2234: 		push(@good_collaborators, @matches);
                   2235: 	    }
                   2236: 	}
                   2237: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2238: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2239: 	    foreach my $name (@good_collaborators) {
                   2240: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2241: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2242: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2243: 	    }
                   2244: 	    $result.='<br />'."\n";
1.466     albertel 2245: 	    my ($part)=split(/\./,$part);
1.464     albertel 2246: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2247: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2248: 		"\n";
                   2249: 	}
                   2250: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2251: 	    $result.='<div class="LC_warning">';
1.464     albertel 2252: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2253: 	    $result .= '</div>';
                   2254: 	}         
                   2255: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2256: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2257: 	    $result .= &mt('This student has submitted too many '.
                   2258: 		'collaborators.  Maximum is [_1].',$ncol);
                   2259: 	    $result .= '</div>';
                   2260: 	}
                   2261:     }
                   2262:     return ($result,$fullname,\@col_fullnames);
                   2263: }
                   2264: 
1.44      ng       2265: #--- Retrieve the last submission for all the parts
1.38      ng       2266: sub get_last_submission {
1.119     ng       2267:     my ($returnhash)=@_;
1.46      ng       2268:     my (@string,$timestamp);
1.119     ng       2269:     if ($$returnhash{'version'}) {
1.46      ng       2270: 	my %lasthash=();
                   2271: 	my ($version);
1.119     ng       2272: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2273: 	    foreach my $key (sort(split(/\:/,
                   2274: 					$$returnhash{$version.':keys'}))) {
                   2275: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2276: 		$timestamp = 
                   2277: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2278: 	    }
                   2279: 	}
1.397     albertel 2280: 	foreach my $key (keys(%lasthash)) {
                   2281: 	    next if ($key !~ /\.submission$/);
                   2282: 
                   2283: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2284: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2285: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2286: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2287: 	}
                   2288:     }
1.397     albertel 2289:     if (!@string) {
                   2290: 	$string[0] =
1.398     albertel 2291: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2292:     }
                   2293:     return (\@string,\$timestamp);
1.38      ng       2294: }
1.35      ng       2295: 
1.44      ng       2296: #--- High light keywords, with style choosen by user.
1.38      ng       2297: sub keywords_highlight {
1.44      ng       2298:     my $string    = shift;
1.257     albertel 2299:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2300:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2301:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2302:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2303:     foreach my $keyword (@keylist) {
                   2304: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2305:     }
                   2306:     return $string;
1.38      ng       2307: }
1.36      ng       2308: 
1.44      ng       2309: #--- Called from submission routine
1.38      ng       2310: sub processHandGrade {
1.41      ng       2311:     my ($request) = shift;
1.324     albertel 2312:     my $symb   = &get_symb($request);
                   2313:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2314:     my $button = $env{'form.gradeOpt'};
                   2315:     my $ngrade = $env{'form.NCT'};
                   2316:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2317:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2318:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2319: 
1.44      ng       2320:     if ($button eq 'Save & Next') {
                   2321: 	my $ctr = 0;
                   2322: 	while ($ctr < $ngrade) {
1.257     albertel 2323: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2324: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2325: 	    if ($errorflag eq 'no_score') {
                   2326: 		$ctr++;
                   2327: 		next;
                   2328: 	    }
1.104     albertel 2329: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2330: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2331: 		$ctr++;
                   2332: 		next;
                   2333: 	    }
1.257     albertel 2334: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2335: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2336: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2337:             my ($feedurl,$showsymb) =
                   2338: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2339: 	    my $messagetail;
1.62      albertel 2340: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2341: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2342: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2343: 		$subject.=' ['.$restitle.']';
1.44      ng       2344: 		my (@msgnum) = split(/,/,$includemsg);
                   2345: 		foreach (@msgnum) {
1.257     albertel 2346: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2347: 		}
1.80      ng       2348: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2349: 		if ($env{'form.withgrades'.$ctr}) {
                   2350: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2351: 		    $messagetail = " for <a href=\"".
1.418     albertel 2352: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2353: 		}
                   2354: 		$msgstatus = 
                   2355:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2356: 						     $message.$messagetail,
1.418     albertel 2357:                                                      undef,$feedurl,undef,
1.386     raeburn  2358:                                                      undef,undef,$showsymb,
                   2359:                                                      $restitle);
                   2360: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2361: 				$msgstatus);
1.44      ng       2362: 	    }
1.257     albertel 2363: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2364: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2365: 		foreach my $collabstr (@collabstrs) {
                   2366: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2367: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2368: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2369: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2370: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2371: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2372: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2373: 			    next;
1.418     albertel 2374: 			} elsif ($message ne '') {
                   2375: 			    my ($baseurl,$showsymb) = 
                   2376: 				&get_feedurl_and_symb($symb,$collaborator,
                   2377: 						      $udom);
                   2378: 			    if ($env{'form.withgrades'.$ctr}) {
                   2379: 				$messagetail = " for <a href=\"".
1.386     raeburn  2380:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2381: 			    }
1.418     albertel 2382: 			    $msgstatus = 
                   2383: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2384: 			}
1.44      ng       2385: 		    }
                   2386: 		}
                   2387: 	    }
                   2388: 	    $ctr++;
                   2389: 	}
                   2390:     }
                   2391: 
1.257     albertel 2392:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2393: 	# Keywords sorted in alphabatical order
1.257     albertel 2394: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2395: 	my %keyhash = ();
1.257     albertel 2396: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2397: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2398: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2399: 	$env{'form.keywords'} = join(' ',@keywords);
                   2400: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2401: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2402: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2403: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2404: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2405: 
                   2406: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2407: 	# New messages are saved in env for the next student.
1.119     ng       2408: 	# All messages are saved in nohist_handgrade.db
                   2409: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2410: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2411: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2412: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2413: 		$idx++;
                   2414: 	    }
                   2415: 	    $ctr++;
1.41      ng       2416: 	}
1.119     ng       2417: 	$ctr = 0;
                   2418: 	while ($ctr < $ngrade) {
1.257     albertel 2419: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2420: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2421: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2422: 		$idx++;
                   2423: 	    }
                   2424: 	    $ctr++;
1.41      ng       2425: 	}
1.257     albertel 2426: 	$env{'form.savemsgN'} = --$idx;
                   2427: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2428: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2429: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2430:     }
1.44      ng       2431:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2432:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2433:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2434: 	my ($ctr,$total) = (0,0);
                   2435: 	while ($ctr < $ngrade) {
1.257     albertel 2436: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2437: 	    $ctr++;
                   2438: 	}
1.257     albertel 2439: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2440: 	$ctr = 0;
                   2441: 	while ($ctr < $total) {
1.257     albertel 2442: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2443: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2444: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2445: 	    &submission($request,$ctr,$total-1);
1.41      ng       2446: 	    $ctr++;
                   2447: 	}
                   2448: 	return '';
                   2449:     }
1.36      ng       2450: 
1.121     ng       2451: # Go directly to grade student - from submission or link from chart page
1.120     ng       2452:     if ($button eq 'Grade Student') {
1.324     albertel 2453: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2454: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2455: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2456: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2457: 	&submission($request,0,0);
                   2458: 	return '';
                   2459:     }
                   2460: 
1.44      ng       2461:     # Get the next/previous one or group of students
1.257     albertel 2462:     my $firststu = $env{'form.unamedom0'};
                   2463:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2464:     my $ctr = 2;
1.41      ng       2465:     while ($laststu eq '') {
1.257     albertel 2466: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2467: 	$ctr++;
                   2468: 	$laststu = $firststu if ($ctr > $ngrade);
                   2469:     }
1.44      ng       2470: 
1.41      ng       2471:     my (@parsedlist,@nextlist);
                   2472:     my ($nextflg) = 0;
1.294     albertel 2473:     foreach (sort 
                   2474: 	     {
                   2475: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2476: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2477: 		 }
                   2478: 		 return $a cmp $b;
                   2479: 	     } (keys(%$fullname))) {
1.41      ng       2480: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2481: 	    push @parsedlist,$_;
                   2482: 	}
                   2483: 	$nextflg = 1 if ($_ eq $laststu);
                   2484: 	if ($button eq 'Previous') {
                   2485: 	    last if ($_ eq $firststu);
                   2486: 	    push @parsedlist,$_;
                   2487: 	}
                   2488:     }
                   2489:     $ctr = 0;
                   2490:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2491:     my ($partlist) = &response_type($symb);
1.41      ng       2492:     foreach my $student (@parsedlist) {
1.257     albertel 2493: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2494: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2495: 	
                   2496: 	if ($submitonly eq 'queued') {
                   2497: 	    my %queue_status = 
                   2498: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2499: 							$udom,$uname);
                   2500: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2501: 	}
                   2502: 
1.156     albertel 2503: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2504: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2505: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2506: 	    my $submitted = 0;
1.248     albertel 2507: 	    my $ungraded = 0;
                   2508: 	    my $incorrect = 0;
1.145     albertel 2509: 	    foreach (keys(%status)) {
                   2510: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2511: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2512: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2513: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2514: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2515: 		    $submitted = 0;
                   2516: 		}
1.41      ng       2517: 	    }
1.156     albertel 2518: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2519: 				     $submitonly eq 'incorrect' ||
                   2520: 				     $submitonly eq 'graded'));
1.248     albertel 2521: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2522: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2523: 	}
                   2524: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2525: 	last if ($ctr == $ntstu);
1.41      ng       2526: 	$ctr++;
                   2527:     }
1.36      ng       2528: 
1.41      ng       2529:     $ctr = 0;
                   2530:     my $total = scalar(@nextlist)-1;
1.39      ng       2531: 
1.41      ng       2532:     foreach (sort @nextlist) {
                   2533: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2534: 	$env{'form.student'}  = $uname;
                   2535: 	$env{'form.userdom'}  = $udom;
                   2536: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2537: 	&submission($request,$ctr,$total);
                   2538: 	$ctr++;
                   2539:     }
                   2540:     if ($total < 0) {
1.485     albertel 2541: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2542: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2543: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2544: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2545: 	$request->print($the_end);
                   2546:     }
                   2547:     return '';
1.38      ng       2548: }
1.36      ng       2549: 
1.44      ng       2550: #---- Save the score and award for each student, if changed
1.38      ng       2551: sub saveHandGrade {
1.324     albertel 2552:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2553:     my @version_parts;
1.104     albertel 2554:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2555: 					   $env{'request.course.id'});
1.104     albertel 2556:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2557:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2558:     my @parts_graded;
1.77      ng       2559:     my %newrecord  = ();
                   2560:     my ($pts,$wgt) = ('','');
1.269     raeburn  2561:     my %aggregate = ();
                   2562:     my $aggregateflag = 0;
1.301     albertel 2563:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2564:     foreach my $new_part (@parts) {
1.337     banghart 2565: 	#collaborator ($submi may vary for different parts
1.259     banghart 2566: 	if ($submitter && $new_part ne $part) { next; }
                   2567: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2568: 	if ($dropMenu eq 'excused') {
1.259     banghart 2569: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2570: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2571: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2572: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2573: 		}
1.364     banghart 2574: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2575: 	    }
1.125     ng       2576: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2577: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2578: 	    foreach my $key (keys (%record)) {
1.259     banghart 2579: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2580: 	    }
1.259     banghart 2581: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2582: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2583:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2584: 
                   2585:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2586: 					       [$new_part]);
                   2587:             my $aggtries =$totaltries;
1.269     raeburn  2588:             if ($last_resets{$new_part}) {
1.270     albertel 2589:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2590: 					   $new_part);
1.269     raeburn  2591:             }
1.270     albertel 2592: 
                   2593:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2594:             if ($aggtries > 0) {
1.327     albertel 2595:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2596:                 $aggregateflag = 1;
                   2597:             }
1.125     ng       2598: 	} elsif ($dropMenu eq '') {
1.259     banghart 2599: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2600: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2601: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2602: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2603: 		next;
                   2604: 	    }
1.259     banghart 2605: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2606: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2607: 	    my $partial= $pts/$wgt;
1.259     banghart 2608: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2609: 		#do not update score for part if not changed.
1.346     banghart 2610:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2611: 		next;
1.251     banghart 2612: 	    } else {
1.259     banghart 2613: 	        push @parts_graded, $new_part;
1.153     albertel 2614: 	    }
1.259     banghart 2615: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2616: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2617: 	    }
1.259     banghart 2618: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2619: 	    if ($partial == 0) {
1.153     albertel 2620: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2621: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2622: 		}
1.41      ng       2623: 	    } else {
1.153     albertel 2624: 		if ($record{$reckey} ne 'correct_by_override') {
                   2625: 		    $newrecord{$reckey} = 'correct_by_override';
                   2626: 		}
                   2627: 	    }	    
                   2628: 	    if ($submitter && 
1.259     banghart 2629: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2630: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2631: 	    }
1.259     banghart 2632: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2633: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2634: 	}
1.259     banghart 2635: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2636: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2637: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2638: 	        $dropMenu eq 'reset status')
                   2639: 	   {
1.342     banghart 2640: 	    push (@version_parts,$new_part);
1.259     banghart 2641: 	}
1.41      ng       2642:     }
1.301     albertel 2643:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2644:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2645: 
1.344     albertel 2646:     if (%newrecord) {
                   2647:         if (@version_parts) {
1.364     banghart 2648:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2649:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2650: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2651: 	    foreach my $new_part (@version_parts) {
                   2652: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2653: 				$new_part,\%newrecord);
                   2654: 	    }
1.259     banghart 2655:         }
1.44      ng       2656: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2657: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2658: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2659: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2660:     }
1.269     raeburn  2661:     if ($aggregateflag) {
                   2662:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2663: 			      $cdom,$cnum);
1.269     raeburn  2664:     }
1.301     albertel 2665:     return ('',$pts,$wgt);
1.36      ng       2666: }
1.322     albertel 2667: 
1.380     albertel 2668: sub check_and_remove_from_queue {
                   2669:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2670:     my @ungraded_parts;
                   2671:     foreach my $part (@{$parts}) {
                   2672: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2673: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2674: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2675: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2676: 		) {
                   2677: 	    push(@ungraded_parts, $part);
                   2678: 	}
                   2679:     }
                   2680:     if ( !@ungraded_parts ) {
                   2681: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2682: 					       $cnum,$domain,$stuname);
                   2683:     }
                   2684: }
                   2685: 
1.337     banghart 2686: sub handback_files {
                   2687:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2688:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2689:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2690: 
                   2691:     my @part_response_id = &flatten_responseType($responseType);
                   2692:     foreach my $part_response_id (@part_response_id) {
                   2693:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2694: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2695:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2696:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2697:                 my $file_counter = 1;
1.367     albertel 2698: 		my $file_msg;
1.337     banghart 2699:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2700:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2701:                     my ($directory,$answer_file) = 
                   2702:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2703:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2704: 		        &file_name_version_ext($answer_file);
1.355     banghart 2705: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2706: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2707: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2708:                     # fix file name
                   2709:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2710:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2711:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2712:             	                                $save_file_name);
1.337     banghart 2713:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2714:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2715:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2716:                     } else {
1.360     banghart 2717:                         # mark the file as read only
                   2718:                         my @files = ($save_file_name);
1.372     albertel 2719:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2720:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2721: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2722: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2723: 			}
                   2724:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2725: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2726: 
1.337     banghart 2727:                     }
                   2728:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2729:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2730:                     $file_counter++;
                   2731:                 }
1.367     albertel 2732: 		my $subject = "File Handed Back by Instructor ";
                   2733: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2734: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2735: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2736: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2737: 		my ($feedurl,$showsymb) = 
                   2738: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2739:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2740: 		my $msgstatus = 
                   2741:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2742: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2743:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2744:             }
                   2745:         }
1.338     banghart 2746:     return;
1.337     banghart 2747: }
                   2748: 
1.418     albertel 2749: sub get_feedurl_and_symb {
                   2750:     my ($symb,$uname,$udom) = @_;
                   2751:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2752:     $url = &Apache::lonnet::clutter($url);
                   2753:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2754: 					$symb,$udom,$uname);
                   2755:     if ($encrypturl =~ /^yes$/i) {
                   2756: 	&Apache::lonenc::encrypted(\$url,1);
                   2757: 	&Apache::lonenc::encrypted(\$symb,1);
                   2758:     }
                   2759:     return ($url,$symb);
                   2760: }
                   2761: 
1.313     banghart 2762: sub get_submitted_files {
                   2763:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2764:     my @files;
                   2765:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2766:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2767:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2768:     	    push(@files,$file_url.$file);
                   2769:         }
                   2770:     }
                   2771:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2772:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2773:     }
                   2774:     return (\@files);
                   2775: }
1.322     albertel 2776: 
1.269     raeburn  2777: # ----------- Provides number of tries since last reset.
                   2778: sub get_num_tries {
                   2779:     my ($record,$last_reset,$part) = @_;
                   2780:     my $timestamp = '';
                   2781:     my $num_tries = 0;
                   2782:     if ($$record{'version'}) {
                   2783:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2784:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2785:                 $timestamp = $$record{$version.':timestamp'};
                   2786:                 if ($timestamp > $last_reset) {
                   2787:                     $num_tries ++;
                   2788:                 } else {
                   2789:                     last;
                   2790:                 }
                   2791:             }
                   2792:         }
                   2793:     }
                   2794:     return $num_tries;
                   2795: }
                   2796: 
                   2797: # ----------- Determine decrements required in aggregate totals 
                   2798: sub decrement_aggs {
                   2799:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2800:     my %decrement = (
                   2801:                         attempts => 0,
                   2802:                         users => 0,
                   2803:                         correct => 0
                   2804:                     );
                   2805:     $decrement{'attempts'} = $aggtries;
                   2806:     if ($solvedstatus =~ /^correct/) {
                   2807:         $decrement{'correct'} = 1;
                   2808:     }
                   2809:     if ($aggtries == $totaltries) {
                   2810:         $decrement{'users'} = 1;
                   2811:     }
                   2812:     foreach my $type (keys (%decrement)) {
                   2813:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2814:     }
                   2815:     return;
                   2816: }
                   2817: 
                   2818: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2819: sub get_last_resets {
1.270     albertel 2820:     my ($symb,$courseid,$partids) =@_;
                   2821:     my %last_resets;
1.269     raeburn  2822:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2823:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2824:     my @keys;
                   2825:     foreach my $part (@{$partids}) {
                   2826: 	push(@keys,"$symb\0$part\0resettime");
                   2827:     }
                   2828:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2829: 				     $cdom,$cname);
                   2830:     foreach my $part (@{$partids}) {
                   2831: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2832:     }
1.270     albertel 2833:     return %last_resets;
1.269     raeburn  2834: }
                   2835: 
1.251     banghart 2836: # ----------- Handles creating versions for portfolio files as answers
                   2837: sub version_portfiles {
1.343     banghart 2838:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2839:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2840:     my @returned_keys;
1.255     banghart 2841:     my $parts = join('|', @$parts_graded);
1.359     www      2842:     my $portfolio_root = &propath($domain,$stu_name).
                   2843: 	'/userfiles/portfolio';
1.277     albertel 2844:     foreach my $key (keys(%$record)) {
1.259     banghart 2845:         my $new_portfiles;
1.263     banghart 2846:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2847:             my @versioned_portfiles;
1.367     albertel 2848:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2849:             foreach my $file (@portfiles) {
1.306     banghart 2850:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2851:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2852: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2853: 		    &file_name_version_ext($answer_file);
1.306     banghart 2854:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2855:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2856:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2857:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2858:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2859:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2860:                         [$directory.$new_answer],
1.306     banghart 2861:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2862:                 }
1.252     banghart 2863:             }
1.343     banghart 2864:             $$record{$key} = join(',',@versioned_portfiles);
                   2865:             push(@returned_keys,$key);
1.251     banghart 2866:         }
                   2867:     } 
1.343     banghart 2868:     return (@returned_keys);   
1.305     banghart 2869: }
                   2870: 
1.307     banghart 2871: sub get_next_version {
1.341     banghart 2872:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2873:     my $version;
                   2874:     foreach my $row (@$dir_list) {
                   2875:         my ($file) = split(/\&/,$row,2);
                   2876:         my ($file_name,$file_version,$file_ext) =
                   2877: 	    &file_name_version_ext($file);
                   2878:         if (($file_name eq $answer_name) && 
                   2879: 	    ($file_ext eq $answer_ext)) {
                   2880:                 # gets here if filename and extension match, regardless of version
                   2881:                 if ($file_version ne '') {
                   2882:                 # a versioned file is found  so save it for later
                   2883:                 if ($file_version > $version) {
                   2884: 		    $version = $file_version;
                   2885: 	        }
                   2886:             }
                   2887:         }
                   2888:     } 
                   2889:     $version ++;
                   2890:     return($version);
                   2891: }
                   2892: 
1.305     banghart 2893: sub version_selected_portfile {
1.306     banghart 2894:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2895:     my ($answer_name,$answer_ver,$answer_ext) =
                   2896:         &file_name_version_ext($file_name);
                   2897:     my $new_answer;
                   2898:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2899:     if($env{'form.copy'} eq '-1') {
                   2900:         $new_answer = 'problem getting file';
                   2901:     } else {
                   2902:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2903:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2904:                             $stu_name,$domain,'copy',
                   2905: 		        '/portfolio'.$directory.$new_answer);
                   2906:     }    
                   2907:     return ($new_answer);
1.251     banghart 2908: }
                   2909: 
1.304     albertel 2910: sub file_name_version_ext {
                   2911:     my ($file)=@_;
                   2912:     my @file_parts = split(/\./, $file);
                   2913:     my ($name,$version,$ext);
                   2914:     if (@file_parts > 1) {
                   2915: 	$ext=pop(@file_parts);
                   2916: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2917: 	    $version=pop(@file_parts);
                   2918: 	}
                   2919: 	$name=join('.',@file_parts);
                   2920:     } else {
                   2921: 	$name=join('.',@file_parts);
                   2922:     }
                   2923:     return($name,$version,$ext);
                   2924: }
                   2925: 
1.44      ng       2926: #--------------------------------------------------------------------------------------
                   2927: #
                   2928: #-------------------------- Next few routines handles grading by section or whole class
                   2929: #
                   2930: #--- Javascript to handle grading by section or whole class
1.42      ng       2931: sub viewgrades_js {
                   2932:     my ($request) = shift;
                   2933: 
1.41      ng       2934:     $request->print(<<VIEWJAVASCRIPT);
                   2935: <script type="text/javascript" language="javascript">
1.45      ng       2936:    function writePoint(partid,weight,point) {
1.125     ng       2937: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2938: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2939: 	if (point == "textval") {
1.125     ng       2940: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2941: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2942: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2943: 		var resetbox = false;
                   2944: 		for (var i=0; i<radioButton.length; i++) {
                   2945: 		    if (radioButton[i].checked) {
                   2946: 			textbox.value = i;
                   2947: 			resetbox = true;
                   2948: 		    }
                   2949: 		}
                   2950: 		if (!resetbox) {
                   2951: 		    textbox.value = "";
                   2952: 		}
                   2953: 		return;
                   2954: 	    }
1.109     matthew  2955: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2956: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2957: 				   ") greater than the weight for the part. Accept?");
                   2958: 		if (resp == false) {
                   2959: 		    textbox.value = "";
                   2960: 		    return;
                   2961: 		}
                   2962: 	    }
1.42      ng       2963: 	    for (var i=0; i<radioButton.length; i++) {
                   2964: 		radioButton[i].checked=false;
1.109     matthew  2965: 		if (parseFloat(point) == i) {
1.42      ng       2966: 		    radioButton[i].checked=true;
                   2967: 		}
                   2968: 	    }
1.41      ng       2969: 
1.42      ng       2970: 	} else {
1.125     ng       2971: 	    textbox.value = parseFloat(point);
1.42      ng       2972: 	}
1.41      ng       2973: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2974: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2975: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2976: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2977: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2978: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2979: 	    if (saveval != "correct") {
                   2980: 		scorename.value = point;
1.43      ng       2981: 		if (selname[0].selected != true) {
                   2982: 		    selname[0].selected = true;
                   2983: 		}
1.42      ng       2984: 	    }
                   2985: 	}
1.125     ng       2986: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2987:     }
                   2988: 
                   2989:     function writeRadText(partid,weight) {
1.125     ng       2990: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2991: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2992:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2993: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2994: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2995: 	    for (var i=0; i<radioButton.length; i++) {
                   2996: 		radioButton[i].checked=false;
                   2997: 
                   2998: 	    }
                   2999: 	    textbox.value = "";
                   3000: 
                   3001: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3002: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3003: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3004: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3005: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3006: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3007: 		if ((saveval != "correct") || override) {
1.42      ng       3008: 		    scorename.value = "";
1.125     ng       3009: 		    if (selval[1].selected) {
                   3010: 			selname[1].selected = true;
                   3011: 		    } else {
                   3012: 			selname[2].selected = true;
                   3013: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3014: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3015: 		    }
1.42      ng       3016: 		}
                   3017: 	    }
1.43      ng       3018: 	} else {
                   3019: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3020: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3021: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3022: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3023: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3024: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3025: 		if ((saveval != "correct") || override) {
1.125     ng       3026: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3027: 		    selname[0].selected = true;
                   3028: 		}
                   3029: 	    }
                   3030: 	}	    
1.42      ng       3031:     }
                   3032: 
                   3033:     function changeSelect(partid,user) {
1.125     ng       3034: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3035: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3036: 	var point  = textbox.value;
1.125     ng       3037: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3038: 
1.109     matthew  3039: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3040: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3041: 	    textbox.value = "";
                   3042: 	    return;
                   3043: 	}
1.109     matthew  3044: 	if (parseFloat(point) > parseFloat(weight)) {
                   3045: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3046: 			       ") greater than the weight of the part. Accept?");
                   3047: 	    if (resp == false) {
                   3048: 		textbox.value = "";
                   3049: 		return;
                   3050: 	    }
                   3051: 	}
1.42      ng       3052: 	selval[0].selected = true;
                   3053:     }
                   3054: 
                   3055:     function changeOneScore(partid,user) {
1.125     ng       3056: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3057: 	if (selval[1].selected || selval[2].selected) {
                   3058: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3059: 	    if (selval[2].selected) {
                   3060: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3061: 	    }
1.269     raeburn  3062:         }
1.42      ng       3063:     }
                   3064: 
                   3065:     function resetEntry(numpart) {
                   3066: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3067: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3068: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3069: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3070: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3071: 	    for (var i=0; i<radioButton.length; i++) {
                   3072: 		radioButton[i].checked=false;
                   3073: 
                   3074: 	    }
                   3075: 	    textbox.value = "";
                   3076: 	    selval[0].selected = true;
                   3077: 
                   3078: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3079: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3080: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3081: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3082: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3083: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3084: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3085: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3086: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3087: 		if (saveselval == "excused") {
1.43      ng       3088: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3089: 		} else {
1.43      ng       3090: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3091: 		}
                   3092: 	    }
1.41      ng       3093: 	}
1.42      ng       3094:     }
                   3095: 
1.41      ng       3096: </script>
                   3097: VIEWJAVASCRIPT
1.42      ng       3098: }
                   3099: 
1.44      ng       3100: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3101: sub viewgrades {
                   3102:     my ($request) = shift;
                   3103:     &viewgrades_js($request);
1.41      ng       3104: 
1.324     albertel 3105:     my ($symb) = &get_symb($request);
1.168     albertel 3106:     #need to make sure we have the correct data for later EXT calls, 
                   3107:     #thus invalidate the cache
                   3108:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3109:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3110:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3111:     &Apache::lonnet::clear_EXT_cache_status();
                   3112: 
1.398     albertel 3113:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3114:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3115: 
                   3116:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3117:     $result.=&jscriptNform($symb);
1.41      ng       3118: 
1.44      ng       3119:     #beginning of class grading form
1.442     banghart 3120:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3121:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3122: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3123: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3124: 	&build_section_inputs().
1.257     albertel 3125: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3126: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3127: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3128: 
1.126     ng       3129:     my $sectionClass;
1.430     banghart 3130:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3131:     if ($env{'form.section'} eq 'all') {
1.485     albertel 3132: 	$sectionClass='Class';
1.257     albertel 3133:     } elsif ($env{'form.section'} eq 'none') {
1.485     albertel 3134: 	$sectionClass='Students in no Section';
1.52      albertel 3135:     } else {
1.485     albertel 3136: 	$sectionClass='Students in Section(s) [_1]';
1.52      albertel 3137:     }
1.485     albertel 3138:     $result.=
                   3139: 	'<h3>'.
                   3140: 	&mt("Assign Common Grade To $sectionClass",$section_display).'</h3>';
1.474     albertel 3141:     $result.= &Apache::loncommon::start_data_table();
1.44      ng       3142:     #radio buttons/text box for assigning points for a section or class.
                   3143:     #handles different parts of a problem
1.375     albertel 3144:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3145:     my %weight = ();
                   3146:     my $ctsparts = 0;
1.45      ng       3147:     my %seen = ();
1.375     albertel 3148:     my @part_response_id = &flatten_responseType($responseType);
                   3149:     foreach my $part_response_id (@part_response_id) {
                   3150:     	my ($partid,$respid) = @{ $part_response_id };
                   3151: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3152: 	next if $seen{$partid};
                   3153: 	$seen{$partid}++;
1.375     albertel 3154: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3155: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3156: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3157: 
1.324     albertel 3158: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3159: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3160: 	my $ctr = 0;
1.42      ng       3161: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3162: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3163: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3164: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3165: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3166: 	    $ctr++;
                   3167: 	}
1.485     albertel 3168: 	$radio.='</tr></table>';
                   3169: 	my $line = '<input type="text" name="TEXTVAL_'.
1.54      albertel 3170: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3171: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3172: 	    $weight{$partid}.' (problem weight)</td>'."\n";
1.485     albertel 3173: 	$line.= '<td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3174: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3175: 		$weight{$partid}.')"> '.
1.401     albertel 3176: 	    '<option selected="selected"> </option>'.
1.485     albertel 3177: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3178: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3179: 	    '</select></td>'.
                   3180:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3181: 	$line.='<input type="hidden" name="partid_'.
                   3182: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3183: 	$line.='<input type="hidden" name="weight_'.
                   3184: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3185: 
                   3186: 	$result.=
                   3187: 	    &Apache::loncommon::start_data_table_row()."\n".
                   3188: 	    &mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line).
                   3189: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3190: 	$ctsparts++;
1.41      ng       3191:     }
1.474     albertel 3192:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3193: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3194:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.474     albertel 3195: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3196: 
1.44      ng       3197:     #table listing all the students in a section/class
                   3198:     #header of table
1.485     albertel 3199:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in '.$sectionClass,
                   3200: 			 $section_display).'</h3>';
1.474     albertel 3201:     $result.= &Apache::loncommon::start_data_table().
                   3202: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 3203: 	'<th>'.&mt('No.').'</th>'.
1.474     albertel 3204: 	'<th>'.&nameUserString('header')."</th>\n";
1.324     albertel 3205:     my (@parts) = sort(&getpartlist($symb));
                   3206:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3207:     my @partids = ();
1.41      ng       3208:     foreach my $part (@parts) {
                   3209: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3210: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3211: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3212: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3213:         push(@partids, $partid);
1.324     albertel 3214: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3215: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3216: 	    $result.='<th>'.
                   3217: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3218: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3219: 	    next;
1.485     albertel 3220: 	    
1.207     albertel 3221: 	} else {
1.485     albertel 3222: 	    if ($display =~ /Problem Status/) {
                   3223: 		my $grade_status_mt = &mt('Grade Status');
                   3224: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3225: 	    }
                   3226: 	    my $part_mt = &mt('Part:');
                   3227: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3228: 	}
1.485     albertel 3229: 
1.474     albertel 3230: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3231:     }
1.474     albertel 3232:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3233: 
1.270     albertel 3234:     my %last_resets = 
                   3235: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3236: 
1.41      ng       3237:     #get info for each student
1.44      ng       3238:     #list all the students - with points and grade status
1.257     albertel 3239:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3240:     my $ctr = 0;
1.294     albertel 3241:     foreach (sort 
                   3242: 	     {
                   3243: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3244: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3245: 		 }
                   3246: 		 return $a cmp $b;
                   3247: 	     } (keys(%$fullname))) {
1.126     ng       3248: 	$ctr++;
1.324     albertel 3249: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3250: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3251:     }
1.474     albertel 3252:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3253:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3254:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.417     albertel 3255: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3256:     if (scalar(%$fullname) eq 0) {
                   3257: 	my $colspan=3+scalar(@parts);
1.433     banghart 3258: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3259:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3260: 	$result='<span class="LC_warning">'.
1.485     albertel 3261: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3262: 	        $section_display, $stu_status).
1.433     banghart 3263: 	    '</span>';
1.96      albertel 3264:     }
1.324     albertel 3265:     $result.=&show_grading_menu_form($symb);
1.41      ng       3266:     return $result;
                   3267: }
                   3268: 
1.44      ng       3269: #--- call by previous routine to display each student
1.41      ng       3270: sub viewstudentgrade {
1.324     albertel 3271:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3272:     my ($uname,$udom) = split(/:/,$student);
                   3273:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3274:     my %aggregates = (); 
1.474     albertel 3275:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3276: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3277: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3278: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3279: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3280: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3281:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3282:     foreach my $apart (@$parts) {
                   3283: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3284: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3285:         $result.='<td align="center">';
1.269     raeburn  3286:         my ($aggtries,$totaltries);
                   3287:         unless (exists($aggregates{$part})) {
1.270     albertel 3288: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3289: 
                   3290: 	    $aggtries = $totaltries;
1.269     raeburn  3291:             if ($$last_resets{$part}) {  
1.270     albertel 3292:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3293: 					   $part);
                   3294:             }
1.269     raeburn  3295:             $result.='<input type="hidden" name="'.
                   3296:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3297:             $result.='<input type="hidden" name="'.
                   3298:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3299:             $aggregates{$part} = 1;
                   3300:         }
1.41      ng       3301: 	if ($type eq 'awarded') {
1.320     albertel 3302: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3303: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3304: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3305: 	    $result.='<input type="text" name="'.
1.89      albertel 3306: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3307: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3308: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3309: 	} elsif ($type eq 'solved') {
                   3310: 	    my ($status,$foo)=split(/_/,$score,2);
                   3311: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3312: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3313: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3314: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3315: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3316: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3317: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3318: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3319: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3320: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3321: 	} else {
                   3322: 	    $result.='<input type="hidden" name="'.
                   3323: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3324: 		    "\n";
1.233     albertel 3325: 	    $result.='<input type="text" name="'.
1.122     ng       3326: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3327: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3328: 	}
                   3329:     }
1.474     albertel 3330:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3331:     return $result;
1.38      ng       3332: }
                   3333: 
1.44      ng       3334: #--- change scores for all the students in a section/class
                   3335: #    record does not get update if unchanged
1.38      ng       3336: sub editgrades {
1.41      ng       3337:     my ($request) = @_;
                   3338: 
1.324     albertel 3339:     my $symb=&get_symb($request);
1.433     banghart 3340:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3341:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3342:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3343:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3344: 
1.477     albertel 3345:     my $result= &Apache::loncommon::start_data_table().
                   3346: 	&Apache::loncommon::start_data_table_header_row().
                   3347: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3348: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3349:     my %scoreptr = (
                   3350: 		    'correct'  =>'correct_by_override',
                   3351: 		    'incorrect'=>'incorrect_by_override',
                   3352: 		    'excused'  =>'excused',
                   3353: 		    'ungraded' =>'ungraded_attempted',
                   3354: 		    'nothing'  => '',
                   3355: 		    );
1.257     albertel 3356:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3357: 
1.44      ng       3358:     my (@partid);
                   3359:     my %weight = ();
1.54      albertel 3360:     my %columns = ();
1.44      ng       3361:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3362: 
1.324     albertel 3363:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3364:     my $header;
1.257     albertel 3365:     while ($ctr < $env{'form.totalparts'}) {
                   3366: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3367: 	push @partid,$partid;
1.257     albertel 3368: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3369: 	$ctr++;
1.54      albertel 3370:     }
1.324     albertel 3371:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3372:     foreach my $partid (@partid) {
1.478     albertel 3373: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3374: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3375: 	$columns{$partid}=2;
                   3376: 	foreach my $stores (@parts) {
                   3377: 	    my ($part,$type) = &split_part_type($stores);
                   3378: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3379: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3380: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3381: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3382: 	    $display =~ s/Number of Attempts/Tries/;
1.478     albertel 3383: 	    $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
                   3384: 		'<th align="center">'.&mt('New '.$display).'</th>';
1.54      albertel 3385: 	    $columns{$partid}+=2;
                   3386: 	}
                   3387:     }
                   3388:     foreach my $partid (@partid) {
1.324     albertel 3389: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3390: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3391: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3392: 	    '</th>';
1.54      albertel 3393: 
1.44      ng       3394:     }
1.477     albertel 3395:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3396: 	&Apache::loncommon::start_data_table_header_row().
                   3397: 	$header.
                   3398: 	&Apache::loncommon::end_data_table_header_row();
                   3399:     my @noupdate;
1.126     ng       3400:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3401:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3402: 	my $line;
1.257     albertel 3403: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3404: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3405: 	my %newrecord;
                   3406: 	my $updateflag = 0;
1.281     albertel 3407: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3408: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3409: 	if (!&canmodify($usec)) {
1.126     ng       3410: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3411: 	    push(@noupdate,
1.478     albertel 3412: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3413: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3414: 	    next;
                   3415: 	}
1.269     raeburn  3416:         my %aggregate = ();
                   3417:         my $aggregateflag = 0;
1.281     albertel 3418: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3419: 	foreach (@partid) {
1.257     albertel 3420: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3421: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3422: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3423: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3424: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3425: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3426: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3427: 	    my $score;
                   3428: 	    if ($partial eq '') {
1.257     albertel 3429: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3430: 	    } elsif ($partial > 0) {
                   3431: 		$score = 'correct_by_override';
                   3432: 	    } elsif ($partial == 0) {
                   3433: 		$score = 'incorrect_by_override';
                   3434: 	    }
1.257     albertel 3435: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3436: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3437: 
1.292     albertel 3438: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3439: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3440: 	    if ($dropMenu eq 'reset status' &&
                   3441: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3442: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3443: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3444: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3445: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3446: 		$updateflag = 1;
1.269     raeburn  3447:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3448:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3449:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3450:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3451:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3452:                     $aggregateflag = 1;
                   3453:                 }
1.139     albertel 3454: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3455: 		$updateflag = 1;
                   3456: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3457: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3458: 		$rec_update++;
1.125     ng       3459: 	    }
                   3460: 
1.93      albertel 3461: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3462: 		'<td align="center">'.$awarded.
                   3463: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3464: 
1.54      albertel 3465: 
                   3466: 	    my $partid=$_;
                   3467: 	    foreach my $stores (@parts) {
                   3468: 		my ($part,$type) = &split_part_type($stores);
                   3469: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3470: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3471: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3472: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3473: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3474: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3475: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3476: 		    $updateflag=1;
                   3477: 		}
1.93      albertel 3478: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3479: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3480: 	    }
1.44      ng       3481: 	}
1.477     albertel 3482: 	$line.="\n";
1.301     albertel 3483: 
                   3484: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3485: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3486: 
1.44      ng       3487: 	if ($updateflag) {
                   3488: 	    $count++;
1.257     albertel 3489: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3490: 				    $udom,$uname);
1.301     albertel 3491: 
                   3492: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3493: 					      $cnum,$udom,$uname)) {
                   3494: 		# need to figure out if should be in queue.
                   3495: 		my %record =  
                   3496: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3497: 					     $udom,$uname);
                   3498: 		my $all_graded = 1;
                   3499: 		my $none_graded = 1;
                   3500: 		foreach my $part (@parts) {
                   3501: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3502: 			$all_graded = 0;
                   3503: 		    } else {
                   3504: 			$none_graded = 0;
                   3505: 		    }
                   3506: 		}
                   3507: 
                   3508: 		if ($all_graded || $none_graded) {
                   3509: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3510: 							   $symb,$cdom,$cnum,
                   3511: 							   $udom,$uname);
                   3512: 		}
                   3513: 	    }
                   3514: 
1.477     albertel 3515: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3516: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3517: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3518: 	    $updateCtr++;
1.93      albertel 3519: 	} else {
1.477     albertel 3520: 	    push(@noupdate,
                   3521: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3522: 	    $noupdateCtr++;
1.44      ng       3523: 	}
1.269     raeburn  3524:         if ($aggregateflag) {
                   3525:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3526: 				  $cdom,$cnum);
1.269     raeburn  3527:         }
1.93      albertel 3528:     }
1.477     albertel 3529:     if (@noupdate) {
1.126     ng       3530: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3531: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3532: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3533: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3534: 	    &mt('No Changes Occurred For the Students Below').
                   3535: 	    '</td>'.
1.477     albertel 3536: 	    &Apache::loncommon::end_data_table_row();
                   3537: 	foreach my $line (@noupdate) {
                   3538: 	    $result.=
                   3539: 		&Apache::loncommon::start_data_table_row().
                   3540: 		$line.
                   3541: 		&Apache::loncommon::end_data_table_row();
                   3542: 	}
1.44      ng       3543:     }
1.477     albertel 3544:     $result .= &Apache::loncommon::end_data_table().
                   3545: 	&show_grading_menu_form($symb);
1.478     albertel 3546:     my $msg = '<p><b>'.
                   3547: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3548: 	    $rec_update,$count).'</b><br />'.
                   3549: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3550: 	'</b></p>';
1.44      ng       3551:     return $title.$msg.$result;
1.5       albertel 3552: }
1.54      albertel 3553: 
                   3554: sub split_part_type {
                   3555:     my ($partstr) = @_;
                   3556:     my ($temp,@allparts)=split(/_/,$partstr);
                   3557:     my $type=pop(@allparts);
1.439     albertel 3558:     my $part=join('_',@allparts);
1.54      albertel 3559:     return ($part,$type);
                   3560: }
                   3561: 
1.44      ng       3562: #------------- end of section for handling grading by section/class ---------
                   3563: #
                   3564: #----------------------------------------------------------------------------
                   3565: 
1.5       albertel 3566: 
1.44      ng       3567: #----------------------------------------------------------------------------
                   3568: #
                   3569: #-------------------------- Next few routines handles grading by csv upload
                   3570: #
                   3571: #--- Javascript to handle csv upload
1.27      albertel 3572: sub csvupload_javascript_reverse_associate {
1.246     albertel 3573:     my $error1=&mt('You need to specify the username or ID');
                   3574:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3575:   return(<<ENDPICK);
                   3576:   function verify(vf) {
                   3577:     var foundsomething=0;
                   3578:     var founduname=0;
1.243     albertel 3579:     var foundID=0;
1.27      albertel 3580:     for (i=0;i<=vf.nfields.value;i++) {
                   3581:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3582:       if (i==0 && tw!=0) { foundID=1; }
                   3583:       if (i==1 && tw!=0) { founduname=1; }
                   3584:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3585:     }
1.246     albertel 3586:     if (founduname==0 && foundID==0) {
                   3587: 	alert('$error1');
                   3588: 	return;
1.27      albertel 3589:     }
                   3590:     if (foundsomething==0) {
1.246     albertel 3591: 	alert('$error2');
                   3592: 	return;
1.27      albertel 3593:     }
                   3594:     vf.submit();
                   3595:   }
                   3596:   function flip(vf,tf) {
                   3597:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3598:     var i;
                   3599:     for (i=0;i<=vf.nfields.value;i++) {
                   3600:       //can not pick the same destination field for both name and domain
                   3601:       if (((i ==0)||(i ==1)) && 
                   3602:           ((tf==0)||(tf==1)) && 
                   3603:           (i!=tf) &&
                   3604:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3605:         eval('vf.f'+i+'.selectedIndex=0;')
                   3606:       }
                   3607:     }
                   3608:   }
                   3609: ENDPICK
                   3610: }
                   3611: 
                   3612: sub csvupload_javascript_forward_associate {
1.246     albertel 3613:     my $error1=&mt('You need to specify the username or ID');
                   3614:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3615:   return(<<ENDPICK);
                   3616:   function verify(vf) {
                   3617:     var foundsomething=0;
                   3618:     var founduname=0;
1.243     albertel 3619:     var foundID=0;
1.27      albertel 3620:     for (i=0;i<=vf.nfields.value;i++) {
                   3621:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3622:       if (tw==1) { foundID=1; }
                   3623:       if (tw==2) { founduname=1; }
                   3624:       if (tw>3) { foundsomething=1; }
1.27      albertel 3625:     }
1.246     albertel 3626:     if (founduname==0 && foundID==0) {
                   3627: 	alert('$error1');
                   3628: 	return;
1.27      albertel 3629:     }
                   3630:     if (foundsomething==0) {
1.246     albertel 3631: 	alert('$error2');
                   3632: 	return;
1.27      albertel 3633:     }
                   3634:     vf.submit();
                   3635:   }
                   3636:   function flip(vf,tf) {
                   3637:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3638:     var i;
                   3639:     //can not pick the same destination field twice
                   3640:     for (i=0;i<=vf.nfields.value;i++) {
                   3641:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3642:         eval('vf.f'+i+'.selectedIndex=0;')
                   3643:       }
                   3644:     }
                   3645:   }
                   3646: ENDPICK
                   3647: }
                   3648: 
1.26      albertel 3649: sub csvuploadmap_header {
1.324     albertel 3650:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3651:     my $javascript;
1.257     albertel 3652:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3653: 	$javascript=&csvupload_javascript_reverse_associate();
                   3654:     } else {
                   3655: 	$javascript=&csvupload_javascript_forward_associate();
                   3656:     }
1.45      ng       3657: 
1.324     albertel 3658:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3659:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3660:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3661:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3662:     $request->print(<<ENDPICK);
1.26      albertel 3663: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3664: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3665: $result
1.326     albertel 3666: <hr />
1.26      albertel 3667: <h3>Identify fields</h3>
                   3668: Total number of records found in file: $distotal <hr />
                   3669: Enter as many fields as you can. The system will inform you and bring you back
                   3670: to this page if the data selected is insufficient to run your class.<hr />
                   3671: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3672: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3673: <input type="hidden" name="associate"  value="" />
                   3674: <input type="hidden" name="phase"      value="three" />
                   3675: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3676: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3677: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3678: <input type="hidden" name="upfile_associate" 
1.257     albertel 3679:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3680: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3681: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3682: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3683: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3684: <hr />
                   3685: <script type="text/javascript" language="Javascript">
                   3686: $javascript
                   3687: </script>
                   3688: ENDPICK
1.118     ng       3689:     return '';
1.26      albertel 3690: 
                   3691: }
                   3692: 
                   3693: sub csvupload_fields {
1.324     albertel 3694:     my ($symb) = @_;
                   3695:     my (@parts) = &getpartlist($symb);
1.243     albertel 3696:     my @fields=(['ID','Student ID'],
                   3697: 		['username','Student Username'],
                   3698: 		['domain','Student Domain']);
1.324     albertel 3699:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3700:     foreach my $part (sort(@parts)) {
                   3701: 	my @datum;
                   3702: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3703: 	my $name=$part;
                   3704: 	if  (!$display) { $display = $name; }
                   3705: 	@datum=($name,$display);
1.244     albertel 3706: 	if ($name=~/^stores_(.*)_awarded/) {
                   3707: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3708: 	}
1.41      ng       3709: 	push(@fields,\@datum);
                   3710:     }
                   3711:     return (@fields);
1.26      albertel 3712: }
                   3713: 
                   3714: sub csvuploadmap_footer {
1.41      ng       3715:     my ($request,$i,$keyfields) =@_;
                   3716:     $request->print(<<ENDPICK);
1.26      albertel 3717: </table>
                   3718: <input type="hidden" name="nfields" value="$i" />
                   3719: <input type="hidden" name="keyfields" value="$keyfields" />
                   3720: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3721: </form>
                   3722: ENDPICK
                   3723: }
                   3724: 
1.283     albertel 3725: sub checkforfile_js {
1.86      ng       3726:     my $result =<<CSVFORMJS;
                   3727: <script type="text/javascript" language="javascript">
                   3728:     function checkUpload(formname) {
                   3729: 	if (formname.upfile.value == "") {
                   3730: 	    alert("Please use the browse button to select a file from your local directory.");
                   3731: 	    return false;
                   3732: 	}
                   3733: 	formname.submit();
                   3734:     }
                   3735:     </script>
                   3736: CSVFORMJS
1.283     albertel 3737:     return $result;
                   3738: }
                   3739: 
                   3740: sub upcsvScores_form {
                   3741:     my ($request) = shift;
1.324     albertel 3742:     my ($symb)=&get_symb($request);
1.283     albertel 3743:     if (!$symb) {return '';}
                   3744:     my $result=&checkforfile_js();
1.257     albertel 3745:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3746:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3747:     $result.=$table;
1.326     albertel 3748:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3749:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3750:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3751: 	'.</b></td></tr>'."\n";
                   3752:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3753:     my $upload=&mt("Upload Scores");
1.86      ng       3754:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3755:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3756:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3757:     $result.=<<ENDUPFORM;
1.106     albertel 3758: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3759: <input type="hidden" name="symb" value="$symb" />
                   3760: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3761: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3762: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3763: $upfile_select
1.370     www      3764: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3765: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3766: </form>
                   3767: ENDUPFORM
1.370     www      3768:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3769:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3770:     .'</td></tr></table>'."\n";
1.86      ng       3771:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3772:     $result.=&show_grading_menu_form($symb);
1.86      ng       3773:     return $result;
                   3774: }
                   3775: 
                   3776: 
1.26      albertel 3777: sub csvuploadmap {
1.41      ng       3778:     my ($request)= @_;
1.324     albertel 3779:     my ($symb)=&get_symb($request);
1.41      ng       3780:     if (!$symb) {return '';}
1.72      ng       3781: 
1.41      ng       3782:     my $datatoken;
1.257     albertel 3783:     if (!$env{'form.datatoken'}) {
1.41      ng       3784: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3785:     } else {
1.257     albertel 3786: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3787: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3788:     }
1.41      ng       3789:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3790:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3791:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3792:     my ($i,$keyfields);
                   3793:     if (@records) {
1.324     albertel 3794: 	my @fields=&csvupload_fields($symb);
1.45      ng       3795: 
1.257     albertel 3796: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3797: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3798: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3799: 							  \@fields);
                   3800: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3801: 	    chop($keyfields);
                   3802: 	} else {
                   3803: 	    unshift(@fields,['none','']);
                   3804: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3805: 							    \@fields);
1.311     banghart 3806:             foreach my $rec (@records) {
                   3807:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3808:                 if (%temp) {
                   3809:                     $keyfields=join(',',sort(keys(%temp)));
                   3810:                     last;
                   3811:                 }
                   3812:             }
1.41      ng       3813: 	}
                   3814:     }
                   3815:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3816:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3817: 
1.41      ng       3818:     return '';
1.27      albertel 3819: }
                   3820: 
1.246     albertel 3821: sub csvuploadoptions {
1.41      ng       3822:     my ($request)= @_;
1.324     albertel 3823:     my ($symb)=&get_symb($request);
1.257     albertel 3824:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3825:     my $ignore=&mt('Ignore First Line');
                   3826:     $request->print(<<ENDPICK);
                   3827: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3828: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3829: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3830: <!--
1.246     albertel 3831: <p>
                   3832: <label>
                   3833:    <input type="checkbox" name="show_full_results" />
                   3834:    Show a table of all changes
                   3835: </label>
                   3836: </p>
1.302     albertel 3837: -->
1.246     albertel 3838: <p>
                   3839: <label>
                   3840:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3841:    Overwrite any existing score
                   3842: </label>
                   3843: </p>
                   3844: ENDPICK
                   3845:     my %fields=&get_fields();
                   3846:     if (!defined($fields{'domain'})) {
1.257     albertel 3847: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3848: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3849:     }
1.257     albertel 3850:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3851: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3852: 	my $cleankey=$1;
                   3853: 	if ($cleankey eq 'command') { next; }
                   3854: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3855: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3856:     }
                   3857:     # FIXME do a check for any duplicated user ids...
                   3858:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3859:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3860: <hr /></form>'."\n");
1.324     albertel 3861:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3862:     return '';
                   3863: }
                   3864: 
                   3865: sub get_fields {
                   3866:     my %fields;
1.257     albertel 3867:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3868:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3869: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3870: 	    if ($env{'form.f'.$i} ne 'none') {
                   3871: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3872: 	    }
                   3873: 	} else {
1.257     albertel 3874: 	    if ($env{'form.f'.$i} ne 'none') {
                   3875: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3876: 	    }
                   3877: 	}
1.27      albertel 3878:     }
1.246     albertel 3879:     return %fields;
                   3880: }
                   3881: 
                   3882: sub csvuploadassign {
                   3883:     my ($request)= @_;
1.324     albertel 3884:     my ($symb)=&get_symb($request);
1.246     albertel 3885:     if (!$symb) {return '';}
1.345     bowersj2 3886:     my $error_msg = '';
1.246     albertel 3887:     &Apache::loncommon::load_tmp_file($request);
                   3888:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3889:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3890:     my %fields=&get_fields();
1.41      ng       3891:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3892:     my $courseid=$env{'request.course.id'};
1.97      albertel 3893:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3894:     my @notallowed;
1.41      ng       3895:     my @skipped;
                   3896:     my $countdone=0;
                   3897:     foreach my $grade (@gradedata) {
                   3898: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3899: 	my $domain;
                   3900: 	if ($entries{$fields{'domain'}}) {
                   3901: 	    $domain=$entries{$fields{'domain'}};
                   3902: 	} else {
1.257     albertel 3903: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3904: 	}
1.243     albertel 3905: 	$domain=~s/\s//g;
1.41      ng       3906: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3907: 	$username=~s/\s//g;
1.243     albertel 3908: 	if (!$username) {
                   3909: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3910: 	    $id=~s/\s//g;
1.243     albertel 3911: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3912: 	    $username=$ids{$id};
                   3913: 	}
1.41      ng       3914: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3915: 	    my $id=$entries{$fields{'ID'}};
                   3916: 	    $id=~s/\s//g;
                   3917: 	    if ($id) {
                   3918: 		push(@skipped,"$id:$domain");
                   3919: 	    } else {
                   3920: 		push(@skipped,"$username:$domain");
                   3921: 	    }
1.41      ng       3922: 	    next;
                   3923: 	}
1.108     albertel 3924: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3925: 	if (!&canmodify($usec)) {
                   3926: 	    push(@notallowed,"$username:$domain");
                   3927: 	    next;
                   3928: 	}
1.244     albertel 3929: 	my %points;
1.41      ng       3930: 	my %grades;
                   3931: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3932: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3933: 		$dest eq 'domain') { next; }
                   3934: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3935: 	    if ($dest=~/stores_(.*)_points/) {
                   3936: 		my $part=$1;
                   3937: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3938: 					      $symb,$domain,$username);
1.345     bowersj2 3939:                 if ($wgt) {
                   3940:                     $entries{$fields{$dest}}=~s/\s//g;
                   3941:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 3942:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   3943:                                           : 'correct_by_override';
1.345     bowersj2 3944:                     $grades{"resource.$part.awarded"}=$pcr;
                   3945:                     $grades{"resource.$part.solved"}=$award;
                   3946:                     $points{$part}=1;
                   3947:                 } else {
                   3948:                     $error_msg = "<br />" .
                   3949:                         &mt("Some point values were assigned"
                   3950:                             ." for problems with a weight "
                   3951:                             ."of zero. These values were "
                   3952:                             ."ignored.");
                   3953:                 }
1.244     albertel 3954: 	    } else {
                   3955: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3956: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3957: 		my $store_key=$dest;
                   3958: 		$store_key=~s/^stores/resource/;
                   3959: 		$store_key=~s/_/\./g;
                   3960: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3961: 	    }
1.41      ng       3962: 	}
1.398     albertel 3963: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3964: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.302     albertel 3965: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3966: 					   $env{'request.course.id'},
                   3967: 					   $domain,$username);
                   3968: 	if ($result eq 'ok') {
                   3969: 	    $request->print('.');
                   3970: 	} else {
                   3971: 	    $request->print("<p>
1.398     albertel 3972:                               <span class=\"LC_error\">
                   3973:                                  Failed to save student $username:$domain.
                   3974:                                  Message when trying to save was ($result)
                   3975:                               </span>
1.302     albertel 3976:                              </p>" );
                   3977: 	}
1.41      ng       3978: 	$request->rflush();
                   3979: 	$countdone++;
                   3980:     }
1.398     albertel 3981:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3982:     if (@skipped) {
1.398     albertel 3983: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3984: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3985:     }
                   3986:     if (@notallowed) {
1.398     albertel 3987: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3988: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3989:     }
1.106     albertel 3990:     $request->print("<br />\n");
1.324     albertel 3991:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3992:     return $error_msg;
1.26      albertel 3993: }
1.44      ng       3994: #------------- end of section for handling csv file upload ---------
                   3995: #
                   3996: #-------------------------------------------------------------------
                   3997: #
1.122     ng       3998: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3999: #
                   4000: #--- Select a page/sequence and a student to grade
1.68      ng       4001: sub pickStudentPage {
                   4002:     my ($request) = shift;
                   4003: 
                   4004:     $request->print(<<LISTJAVASCRIPT);
                   4005: <script type="text/javascript" language="javascript">
                   4006: 
                   4007: function checkPickOne(formname) {
1.76      ng       4008:     if (radioSelection(formname.student) == null) {
1.68      ng       4009: 	alert("Please select the student you wish to grade.");
                   4010: 	return;
                   4011:     }
1.125     ng       4012:     ptr = pullDownSelection(formname.selectpage);
                   4013:     formname.page.value = formname["page"+ptr].value;
                   4014:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4015:     formname.submit();
                   4016: }
                   4017: 
                   4018: </script>
                   4019: LISTJAVASCRIPT
1.118     ng       4020:     &commonJSfunctions($request);
1.324     albertel 4021:     my ($symb) = &get_symb($request);
1.257     albertel 4022:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4023:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4024:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4025: 
1.398     albertel 4026:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4027: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4028: 
1.80      ng       4029:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.423     albertel 4030:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4031:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4032: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4033: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4034:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4035:     my $ctr=0;
1.68      ng       4036:     foreach (@$titles) {
                   4037: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4038: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4039: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4040: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4041: 	$ctr++;
1.68      ng       4042:     }
1.485     albertel 4043:     $select.= '</select>';
                   4044:     $result.=&mt('&nbsp;<b>Problems from:</b> [_1]',$select)."<br />\n";
                   4045: 
1.70      ng       4046:     $ctr=0;
                   4047:     foreach (@$titles) {
                   4048: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4049: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4050: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4051: 	$ctr++;
                   4052:     }
1.72      ng       4053:     $result.='<input type="hidden" name="page" />'."\n".
                   4054: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4055: 
1.485     albertel 4056:     my $options =
                   4057: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4058: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
                   4059:     $result.='&nbsp;'.&mt('<b>View Problems Text: </b> [_1]',$options);
                   4060: 
                   4061:     $options =
                   4062: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4063: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4064: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
                   4065:     $result.='&nbsp;'.&mt('<b>Submission Details: </b>[_1]',$options);
1.432     banghart 4066:     
                   4067:     $result.=&build_section_inputs();
1.442     banghart 4068:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4069:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4070: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4071: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4072: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4073: 
1.485     albertel 4074:     $result.='&nbsp;'.&mt('<b>Use CODE: [_1] </b>',
                   4075: 			  '<input type="text" name="CODE" value="" />').
                   4076: 			      '<br />'."\n";
1.382     albertel 4077: 
1.80      ng       4078:     $result.='&nbsp;<input type="button" '.
1.485     albertel 4079: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /><br />'."\n";
1.72      ng       4080: 
1.68      ng       4081:     $request->print($result);
                   4082: 
1.485     albertel 4083:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4084: 	&Apache::loncommon::start_data_table().
                   4085: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4086: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4087: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4088: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4089: 	'<th>'.&nameUserString('header').'</th>'.
                   4090: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4091:  
1.76      ng       4092:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4093:     my $ptr = 1;
1.294     albertel 4094:     foreach my $student (sort 
                   4095: 			 {
                   4096: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4097: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4098: 			     }
                   4099: 			     return $a cmp $b;
                   4100: 			 } (keys(%$fullname))) {
1.68      ng       4101: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4102: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4103:                                   : '</td>');
1.126     ng       4104: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4105: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4106: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4107: 	$studentTable.=
                   4108: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4109:                          : '');
1.68      ng       4110: 	$ptr++;
                   4111:     }
1.484     albertel 4112:     if ($ptr%2 == 0) {
                   4113: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4114: 	    &Apache::loncommon::end_data_table_row();
                   4115:     }
                   4116:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4117:     $studentTable.='<input type="button" '.
1.485     albertel 4118: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /></form>'."\n";
1.68      ng       4119: 
1.324     albertel 4120:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4121:     $request->print($studentTable);
                   4122: 
                   4123:     return '';
                   4124: }
                   4125: 
                   4126: sub getSymbMap {
1.132     bowersj2 4127:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4128: 
                   4129:     my %symbx = ();
                   4130:     my @titles = ();
1.117     bowersj2 4131:     my $minder = 0;
                   4132: 
                   4133:     # Gather every sequence that has problems.
1.240     albertel 4134:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4135: 					       1,0,1);
1.117     bowersj2 4136:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4137: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4138: 	    my $title = $minder.'.'.
                   4139: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4140: 	    push(@titles, $title); # minder in case two titles are identical
                   4141: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4142: 	    $minder++;
1.241     albertel 4143: 	}
1.68      ng       4144:     }
                   4145:     return \@titles,\%symbx;
                   4146: }
                   4147: 
1.72      ng       4148: #
                   4149: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4150: sub displayPage {
                   4151:     my ($request) = shift;
                   4152: 
1.324     albertel 4153:     my ($symb) = &get_symb($request);
1.257     albertel 4154:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4155:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4156:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4157:     my $pageTitle = $env{'form.page'};
1.103     albertel 4158:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4159:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4160:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4161: 
                   4162:     #need to make sure we have the correct data for later EXT calls, 
                   4163:     #thus invalidate the cache
                   4164:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4165:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4166:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4167:     &Apache::lonnet::clear_EXT_cache_status();
                   4168: 
1.103     albertel 4169:     if (!&canview($usec)) {
1.485     albertel 4170: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4171: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4172: 	return;
                   4173:     }
1.398     albertel 4174:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4175:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4176: 	'</h3>'."\n";
1.382     albertel 4177:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
1.485     albertel 4178: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4179:     } else {
                   4180: 	delete($env{'form.CODE'});
                   4181:     }
1.71      ng       4182:     &sub_page_js($request);
                   4183:     $request->print($result);
                   4184: 
1.132     bowersj2 4185:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4186:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4187:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4188:     if (!$map) {
1.485     albertel 4189: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4190: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4191: 	return; 
                   4192:     }
1.68      ng       4193:     my $iterator = $navmap->getIterator($map->map_start(),
                   4194: 					$map->map_finish());
                   4195: 
1.71      ng       4196:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4197: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4198: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4199: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4200: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4201: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4202: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4203: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4204: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4205: 
1.382     albertel 4206:     if (defined($env{'form.CODE'})) {
                   4207: 	$studentTable.=
                   4208: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4209:     }
1.381     albertel 4210:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4211: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4212: 
1.485     albertel 4213:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
1.484     albertel 4214: 	&Apache::loncommon::start_data_table().
                   4215: 	&Apache::loncommon::start_data_table_header_row().
                   4216: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4217: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4218: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4219: 
1.329     albertel 4220:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4221:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4222:     $iterator->next(); # skip the first BEGIN_MAP
                   4223:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4224:     while ($depth > 0) {
1.68      ng       4225:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4226:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4227: 
1.385     albertel 4228:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4229: 	    my $parts = $curRes->parts();
1.68      ng       4230:             my $title = $curRes->compTitle();
1.71      ng       4231: 	    my $symbx = $curRes->symb();
1.484     albertel 4232: 	    $studentTable.=
                   4233: 		&Apache::loncommon::start_data_table_row().
                   4234: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4235: 		(scalar(@{$parts}) == 1 ? '' 
                   4236: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4237: 							scalar(@{$parts}))
                   4238: 		 ).
                   4239: 		 '</td>';
1.71      ng       4240: 	    $studentTable.='<td valign="top">';
1.382     albertel 4241: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4242: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4243: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4244: 					     undef,'both',\%form);
1.71      ng       4245: 	    } else {
1.382     albertel 4246: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4247: 		$companswer =~ s|<form(.*?)>||g;
                   4248: 		$companswer =~ s|</form>||g;
1.71      ng       4249: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4250: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4251: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4252: #		}
1.116     ng       4253: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.485     albertel 4254: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;'.&mt('<b>Correct answer:</b><br />[_1]',$companswer);
1.71      ng       4255: 	    }
                   4256: 
1.257     albertel 4257: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4258: 
1.257     albertel 4259: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4260: 		if ($record{'version'} eq '') {
1.485     albertel 4261: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4262: 		} else {
1.116     ng       4263: 		    my %responseType = ();
                   4264: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4265: 			my @responseIds =$curRes->responseIds($partid);
                   4266: 			my @responseType =$curRes->responseType($partid);
                   4267: 			my %responseIds;
                   4268: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4269: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4270: 			}
                   4271: 			$responseType{$partid} = \%responseIds;
1.116     ng       4272: 		    }
1.148     albertel 4273: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4274: 
1.71      ng       4275: 		}
1.257     albertel 4276: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4277: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4278: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4279: 									$env{'request.course.id'},
1.71      ng       4280: 									'','.submission');
                   4281:  
                   4282: 	    }
1.103     albertel 4283: 	    if (&canmodify($usec)) {
                   4284: 		foreach my $partid (@{$parts}) {
                   4285: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4286: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4287: 		    $question++;
                   4288: 		}
1.196     albertel 4289: 		$prob++;
1.71      ng       4290: 	    }
                   4291: 	    $studentTable.='</td></tr>';
1.68      ng       4292: 
1.103     albertel 4293: 	}
1.68      ng       4294:         $curRes = $iterator->next();
                   4295:     }
                   4296: 
1.485     albertel 4297:     $studentTable.='</table>'."\n".
                   4298: 	'<input type="button" value="'.&mt('Save').'" '.
1.381     albertel 4299: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4300: 	'</form>'."\n";
1.324     albertel 4301:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4302:     $request->print($studentTable);
                   4303: 
                   4304:     return '';
1.119     ng       4305: }
                   4306: 
                   4307: sub displaySubByDates {
1.148     albertel 4308:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4309:     my $isCODE=0;
1.335     albertel 4310:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4311:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4312:     my $studentTable=&Apache::loncommon::start_data_table().
                   4313: 	&Apache::loncommon::start_data_table_header_row().
                   4314: 	'<th>'.&mt('Date/Time').'</th>'.
                   4315: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4316: 	'<th>'.&mt('Submission').'</th>'.
                   4317: 	'<th>'.&mt('Status').'</th>'.
                   4318: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4319:     my ($version);
                   4320:     my %mark;
1.148     albertel 4321:     my %orders;
1.119     ng       4322:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4323:     if (!exists($$record{'1:timestamp'})) {
1.467     albertel 4324: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
1.147     albertel 4325:     }
1.335     albertel 4326: 
                   4327:     my $interaction;
1.119     ng       4328:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4329: 	my $timestamp = 
                   4330: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4331: 	if (exists($$record{$version.':resource.0.version'})) {
                   4332: 	    $interaction = $$record{$version.':resource.0.version'};
                   4333: 	}
                   4334: 
                   4335: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4336: 		             : "$version:resource");
1.467     albertel 4337: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4338: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4339: 	if ($isCODE) {
                   4340: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4341: 	}
1.119     ng       4342: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4343: 	my @displaySub = ();
                   4344: 	foreach my $partid (@{$parts}) {
1.335     albertel 4345: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4346: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4347: 	    
                   4348: 
1.122     ng       4349: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4350: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4351: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4352: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4353: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4354: 
                   4355: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4356: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.467     albertel 4357: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
                   4358: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
1.398     albertel 4359: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4360: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.467     albertel 4361: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
1.147     albertel 4362: 		    } else {
1.467     albertel 4363: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
                   4364: 					    $$record{"$where.$partid.tries"});
1.147     albertel 4365: 		    }
1.335     albertel 4366: 		    my $responseType=($isTask ? 'Task'
                   4367:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4368: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4369: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4370: 			$orders{$partid}->{$responseId}=
                   4371: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4372: 		    }
1.147     albertel 4373: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4374: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4375: 		}
                   4376: 	    }
1.335     albertel 4377: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4378: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4379: 				    $$record{"$where.$partid.checkedin"},
                   4380: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4381: 					'<br />';
1.335     albertel 4382: 	    }
                   4383: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4384: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4385: 		    lc($$record{"$where.$partid.award"}).' '.
                   4386: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4387: 		    '<br />';
                   4388: 	    }
1.335     albertel 4389: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4390: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4391: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4392: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4393: 		$displaySub[2].=
                   4394: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4395: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4396: 	    }
                   4397: 	}
                   4398: 	# needed because old essay regrader has not parts info
                   4399: 	if (exists $$record{"$version:resource.regrader"}) {
                   4400: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4401: 	}
                   4402: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4403: 	if ($displaySub[2]) {
1.467     albertel 4404: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4405: 	}
1.467     albertel 4406: 	$studentTable.='&nbsp;</td>'.
                   4407: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4408:     }
1.467     albertel 4409:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4410:     return $studentTable;
1.71      ng       4411: }
                   4412: 
                   4413: sub updateGradeByPage {
                   4414:     my ($request) = shift;
                   4415: 
1.257     albertel 4416:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4417:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4418:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4419:     my $pageTitle = $env{'form.page'};
1.103     albertel 4420:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4421:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4422:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4423:     if (!&canmodify($usec)) {
1.398     albertel 4424: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4425: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4426: 	return;
                   4427:     }
1.398     albertel 4428:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4429:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4430: 	'</h3>'."\n";
1.70      ng       4431: 
1.68      ng       4432:     $request->print($result);
                   4433: 
1.132     bowersj2 4434:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4435:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4436:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4437:     if (!$map) {
1.398     albertel 4438: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4439: 	my ($symb)=&get_symb($request);
                   4440: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4441: 	return; 
                   4442:     }
1.71      ng       4443:     my $iterator = $navmap->getIterator($map->map_start(),
                   4444: 					$map->map_finish());
1.70      ng       4445: 
1.484     albertel 4446:     my $studentTable=
                   4447: 	&Apache::loncommon::start_data_table().
                   4448: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4449: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4450: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4451: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4452: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4453: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4454: 
                   4455:     $iterator->next(); # skip the first BEGIN_MAP
                   4456:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4457:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4458:     while ($depth > 0) {
1.71      ng       4459:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4460:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4461: 
1.385     albertel 4462:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4463: 	    my $parts = $curRes->parts();
1.71      ng       4464:             my $title = $curRes->compTitle();
                   4465: 	    my $symbx = $curRes->symb();
1.484     albertel 4466: 	    $studentTable.=
                   4467: 		&Apache::loncommon::start_data_table_row().
                   4468: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4469: 		(scalar(@{$parts}) == 1 ? '' 
                   4470:                                         : '<br />('.&mt('[quant,_1,&nbsp;parts]',scalar(@{$parts}))
                   4471: 		 ).')</td>';
1.71      ng       4472: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4473: 
                   4474: 	    my %newrecord=();
                   4475: 	    my @displayPts=();
1.269     raeburn  4476:             my %aggregate = ();
                   4477:             my $aggregateflag = 0;
1.71      ng       4478: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4479: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4480: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4481: 
1.257     albertel 4482: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4483: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4484: 		my $partial = $newpts/$wgt;
                   4485: 		my $score;
                   4486: 		if ($partial > 0) {
                   4487: 		    $score = 'correct_by_override';
1.125     ng       4488: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4489: 		    $score = 'incorrect_by_override';
                   4490: 		}
1.257     albertel 4491: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4492: 		if ($dropMenu eq 'excused') {
1.71      ng       4493: 		    $partial = '';
                   4494: 		    $score = 'excused';
1.125     ng       4495: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4496: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4497: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4498: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4499: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4500: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4501: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4502: 		    $changeflag++;
                   4503: 		    $newpts = '';
1.269     raeburn  4504:                     
                   4505:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4506:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4507:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4508:                     if ($aggtries > 0) {
                   4509:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4510:                         $aggregateflag = 1;
                   4511:                     }
1.71      ng       4512: 		}
1.324     albertel 4513: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4514: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4515: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4516: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4517: 		    '&nbsp;<br />';
1.207     albertel 4518: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4519: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4520: 		    '&nbsp;<br />';
1.71      ng       4521: 		$question++;
1.380     albertel 4522: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4523: 
1.71      ng       4524: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4525: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4526: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4527: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4528: 
                   4529: 		$changeflag++;
                   4530: 	    }
                   4531: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4532: 		my %record = 
                   4533: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4534: 					     $udom,$uname);
                   4535: 
                   4536: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4537: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4538: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4539: 		    $newrecord{'resource.CODE'} = '';
                   4540: 		}
1.257     albertel 4541: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4542: 					$udom,$uname);
1.382     albertel 4543: 		%record = &Apache::lonnet::restore($symbx,
                   4544: 						   $env{'request.course.id'},
                   4545: 						   $udom,$uname);
1.380     albertel 4546: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4547: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4548: 	    }
1.380     albertel 4549: 	    
1.269     raeburn  4550:             if ($aggregateflag) {
                   4551:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4552:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4553:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4554:             }
1.125     ng       4555: 
1.71      ng       4556: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4557: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4558: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4559: 
1.196     albertel 4560: 	    $prob++;
1.68      ng       4561: 	}
1.71      ng       4562:         $curRes = $iterator->next();
1.68      ng       4563:     }
1.98      albertel 4564: 
1.484     albertel 4565:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4566:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4567:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4568: 		  'The scores were changed for '.
                   4569: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4570:     $request->print($grademsg.$studentTable);
1.68      ng       4571: 
1.70      ng       4572:     return '';
                   4573: }
                   4574: 
1.72      ng       4575: #-------- end of section for handling grading by page/sequence ---------
                   4576: #
                   4577: #-------------------------------------------------------------------
                   4578: 
1.75      albertel 4579: #--------------------Scantron Grading-----------------------------------
                   4580: #
                   4581: #------ start of section for handling grading by page/sequence ---------
                   4582: 
1.423     albertel 4583: =pod
                   4584: 
                   4585: =head1 Bubble sheet grading routines
                   4586: 
1.424     albertel 4587:   For this documentation:
                   4588: 
                   4589:    'scanline' refers to the full line of characters
                   4590:    from the file that we are parsing that represents one entire sheet
                   4591: 
                   4592:    'bubble line' refers to the data
                   4593:    representing the line of bubbles that are on the physical bubble sheet
                   4594: 
                   4595: 
                   4596: The overall process is that a scanned in bubble sheet data is uploaded
                   4597: into a course. When a user wants to grade, they select a
                   4598: sequence/folder of resources, a file of bubble sheet info, and pick
                   4599: one of the predefined configurations for what each scanline looks
                   4600: like.
                   4601: 
                   4602: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4603: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4604: because too light bubbling), 'double bubble' (each bubble line should
                   4605: have no more that one letter picked), invalid or duplicated CODE,
                   4606: invalid student ID
                   4607: 
                   4608: If the CODE option is used that determines the randomization of the
                   4609: homework problems, either way the student ID is looked up into a
                   4610: username:domain.
                   4611: 
                   4612: During the validation phase the instructor can choose to skip scanlines. 
                   4613: 
1.435     foxr     4614: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4615: 
                   4616:   scantron_original_filename (unmodified original file)
                   4617:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4618:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4619: 
                   4620: Also there is a separate hash nohist_scantrondata that contains extra
                   4621: correction information that isn't representable in the bubble sheet
                   4622: file (see &scantron_getfile() for more information)
                   4623: 
                   4624: After all scanlines are either valid, marked as valid or skipped, then
                   4625: foreach line foreach problem in the picked sequence, an ssi request is
                   4626: made that simulates a user submitting their selected letter(s) against
                   4627: the homework problem.
1.423     albertel 4628: 
                   4629: =over 4
                   4630: 
                   4631: 
                   4632: 
                   4633: =item defaultFormData
                   4634: 
                   4635:   Returns html hidden inputs used to hold context/default values.
                   4636: 
                   4637:  Arguments:
                   4638:   $symb - $symb of the current resource 
                   4639: 
                   4640: =cut
1.422     foxr     4641: 
1.81      albertel 4642: sub defaultFormData {
1.324     albertel 4643:     my ($symb)=@_;
1.447     foxr     4644:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4645:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4646:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4647: }
                   4648: 
1.447     foxr     4649: 
1.423     albertel 4650: =pod 
                   4651: 
                   4652: =item getSequenceDropDown
                   4653: 
                   4654:    Return html dropdown of possible sequences to grade
                   4655:  
                   4656:  Arguments:
                   4657:    $symb - $symb of the current resource 
                   4658: 
                   4659: =cut
1.422     foxr     4660: 
1.75      albertel 4661: sub getSequenceDropDown {
1.423     albertel 4662:     my ($symb)=@_;
1.75      albertel 4663:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4664:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4665:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4666:     my $ctr=0;
                   4667:     foreach (@$titles) {
                   4668: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4669: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4670: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4671: 	    '>'.$showtitle.'</option>'."\n";
                   4672: 	$ctr++;
                   4673:     }
                   4674:     $result.= '</select>';
                   4675:     return $result;
                   4676: }
                   4677: 
1.495   ! albertel 4678: my %bubble_lines_per_response;     # no. bubble lines for each response.
        !          4679:                                    # index is "symb.part_id"
        !          4680: 
        !          4681: my %first_bubble_line;             # First bubble line no. for each bubble.
        !          4682: 
        !          4683: # Save and restore the bubble lines array to the form env.
        !          4684: 
        !          4685: 
        !          4686: sub save_bubble_lines {
        !          4687:     foreach my $line (keys(%bubble_lines_per_response)) {
        !          4688: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
        !          4689: 	$env{"form.scantron.first_bubble_line.$line"} =
        !          4690: 	    $first_bubble_line{$line};
        !          4691:     }
        !          4692: }
        !          4693: 
        !          4694: 
        !          4695: sub restore_bubble_lines {
        !          4696:     my $line = 0;
        !          4697:     %bubble_lines_per_response = ();
        !          4698:     while ($env{"form.scantron.bubblelines.$line"}) {
        !          4699: 	my $value = $env{"form.scantron.bubblelines.$line"};
        !          4700: 	$bubble_lines_per_response{$line} = $value;
        !          4701: 	$first_bubble_line{$line}  =
        !          4702: 	    $env{"form.scantron.first_bubble_line.$line"};
        !          4703: 	$line++;
        !          4704:     }
        !          4705: 
        !          4706: }
        !          4707: 
        !          4708: #  Given the parsed scanline, get the response for 
        !          4709: #  'answer' number n:
        !          4710: 
        !          4711: sub get_response_bubbles {
        !          4712:     my ($parsed_line, $response)  = @_;
        !          4713: 
        !          4714: 
        !          4715:     my $bubble_line = $first_bubble_line{$response-1} +1;
        !          4716:     my $bubble_lines= $bubble_lines_per_response{$response-1};
        !          4717:     
        !          4718:     my $selected = "";
        !          4719: 
        !          4720:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
        !          4721: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
        !          4722: 	$bubble_line++;
        !          4723:     }
        !          4724:     return $selected;
        !          4725: }
1.423     albertel 4726: 
                   4727: =pod 
                   4728: 
                   4729: =item scantron_filenames
                   4730: 
                   4731:    Returns a list of the scantron files in the current course 
                   4732: 
                   4733: =cut
1.422     foxr     4734: 
1.202     albertel 4735: sub scantron_filenames {
1.257     albertel 4736:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4737:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4738:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4739: 				    &propath($cdom,$cname));
1.202     albertel 4740:     my @possiblenames;
1.201     albertel 4741:     foreach my $filename (sort(@files)) {
1.157     albertel 4742: 	($filename)=split(/&/,$filename);
                   4743: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4744: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4745: 	push(@possiblenames,$filename);
                   4746:     }
                   4747:     return @possiblenames;
                   4748: }
                   4749: 
1.423     albertel 4750: =pod 
                   4751: 
                   4752: =item scantron_uploads
                   4753: 
                   4754:    Returns  html drop-down list of scantron files in current course.
                   4755: 
                   4756:  Arguments:
                   4757:    $file2grade - filename to set as selected in the dropdown
                   4758: 
                   4759: =cut
1.422     foxr     4760: 
1.202     albertel 4761: sub scantron_uploads {
1.209     ng       4762:     my ($file2grade) = @_;
1.202     albertel 4763:     my $result=	'<select name="scantron_selectfile">';
                   4764:     $result.="<option></option>";
                   4765:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4766: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4767:     }
                   4768:     $result.="</select>";
                   4769:     return $result;
                   4770: }
                   4771: 
1.423     albertel 4772: =pod 
                   4773: 
                   4774: =item scantron_scantab
                   4775: 
                   4776:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4777:   file.
                   4778: 
                   4779: =cut
1.422     foxr     4780: 
1.82      albertel 4781: sub scantron_scantab {
                   4782:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4783:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4784:     $result.='<option></option>'."\n";
1.82      albertel 4785:     foreach my $line (<$fh>) {
                   4786: 	my ($name,$descrip)=split(/:/,$line);
                   4787: 	if ($name =~ /^\#/) { next; }
                   4788: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4789:     }
                   4790:     $result.='</select>'."\n";
                   4791: 
                   4792:     return $result;
                   4793: }
                   4794: 
1.423     albertel 4795: =pod 
                   4796: 
                   4797: =item scantron_CODElist
                   4798: 
                   4799:   Returns html drop down of the saved CODE lists from current course,
                   4800:   generated from earlier printings.
                   4801: 
                   4802: =cut
1.422     foxr     4803: 
1.186     albertel 4804: sub scantron_CODElist {
1.257     albertel 4805:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4806:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4807:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4808:     my $namechoice='<option></option>';
1.225     albertel 4809:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4810: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4811: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4812: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4813:     }
                   4814:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4815:     return $namechoice;
                   4816: }
                   4817: 
1.423     albertel 4818: =pod 
                   4819: 
                   4820: =item scantron_CODEunique
                   4821: 
                   4822:   Returns the html for "Each CODE to be used once" radio.
                   4823: 
                   4824: =cut
1.422     foxr     4825: 
1.186     albertel 4826: sub scantron_CODEunique {
1.381     albertel 4827:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4828:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4829:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4830:                 </span>
                   4831:                 <span style="white-space: nowrap;">
1.272     albertel 4832:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4833:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4834:                 </span>';
1.186     albertel 4835:     return $result;
                   4836: }
1.423     albertel 4837: 
                   4838: =pod 
                   4839: 
                   4840: =item scantron_selectphase
                   4841: 
                   4842:   Generates the initial screen to start the bubble sheet process.
                   4843:   Allows for - starting a grading run.
1.424     albertel 4844:              - downloading existing scan data (original, corrected
1.423     albertel 4845:                                                 or skipped info)
                   4846: 
                   4847:              - uploading new scan data
                   4848: 
                   4849:  Arguments:
                   4850:   $r          - The Apache request object
                   4851:   $file2grade - name of the file that contain the scanned data to score
                   4852: 
                   4853: =cut
1.186     albertel 4854: 
1.75      albertel 4855: sub scantron_selectphase {
1.209     ng       4856:     my ($r,$file2grade) = @_;
1.324     albertel 4857:     my ($symb)=&get_symb($r);
1.75      albertel 4858:     if (!$symb) {return '';}
1.423     albertel 4859:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4860:     my $default_form_data=&defaultFormData($symb);
                   4861:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4862:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4863:     my $format_selector=&scantron_scantab();
1.186     albertel 4864:     my $CODE_selector=&scantron_CODElist();
                   4865:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4866:     my $result;
1.422     foxr     4867: 
                   4868:     # Chunk of form to prompt for a file to grade and how:
                   4869: 
1.489     albertel 4870:     $result.= '
                   4871:     <br />
                   4872:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   4873:     <input type="hidden" name="command" value="scantron_warning" />
                   4874:     '.$default_form_data.'
                   4875:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   4876:        '.&Apache::loncommon::start_data_table_header_row().'
                   4877:             <th colspan="2">
1.492     albertel 4878:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 4879:             </th>
                   4880:        '.&Apache::loncommon::end_data_table_header_row().'
                   4881:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4882:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 4883:        '.&Apache::loncommon::end_data_table_row().'
                   4884:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4885:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 4886:        '.&Apache::loncommon::end_data_table_row().'
                   4887:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4888:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 4889:        '.&Apache::loncommon::end_data_table_row().'
                   4890:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4891:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 4892:        '.&Apache::loncommon::end_data_table_row().'
                   4893:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4894:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 4895:        '.&Apache::loncommon::end_data_table_row().'
                   4896:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4897: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 4898:             <td>
1.492     albertel 4899: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   4900:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   4901:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 4902: 	    </td>
1.489     albertel 4903:        '.&Apache::loncommon::end_data_table_row().'
                   4904:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 4905:             <td colspan="2">
1.492     albertel 4906:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
1.162     albertel 4907:             </td>
1.489     albertel 4908:        '.&Apache::loncommon::end_data_table_row().'
                   4909:     '.&Apache::loncommon::end_data_table().'
                   4910:     </form>
                   4911: ';
1.162     albertel 4912:    
                   4913:     $r->print($result);
                   4914: 
1.257     albertel 4915:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4916:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4917: 
1.422     foxr     4918: 	# Chunk of form to prompt for a scantron file upload.
                   4919: 
1.489     albertel 4920:         $r->print('
                   4921:     <br />
                   4922:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   4923:        '.&Apache::loncommon::start_data_table_header_row().'
                   4924:             <th>
1.492     albertel 4925:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
1.489     albertel 4926:             </th>
                   4927:        '.&Apache::loncommon::end_data_table_header_row().'
                   4928:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 4929:             <td>
1.489     albertel 4930: ');
1.324     albertel 4931:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4932:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4933:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.492     albertel 4934:     $r->print('
1.174     albertel 4935:               <script type="text/javascript" language="javascript">
                   4936:     function checkUpload(formname) {
                   4937: 	if (formname.upfile.value == "") {
1.492     albertel 4938: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 4939: 	    return false;
                   4940: 	}
                   4941: 	formname.submit();
                   4942:     }
                   4943:               </script>
                   4944: 
1.492     albertel 4945:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   4946:                 '.$default_form_data.'
                   4947:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   4948:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   4949:                 <input name="command" value="scantronupload_save" type="hidden" />
                   4950:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 4951:                 <br />
1.492     albertel 4952:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.174     albertel 4953:               </form>
1.492     albertel 4954: ');
1.162     albertel 4955: 
1.489     albertel 4956:         $r->print('
1.162     albertel 4957:             </td>
1.489     albertel 4958:        '.&Apache::loncommon::end_data_table_row().'
                   4959:        '.&Apache::loncommon::end_data_table().'
                   4960: ');
1.162     albertel 4961:     }
1.422     foxr     4962: 
                   4963:     # Chunk of the form that prompts to view a scoring office file,
                   4964:     # corrected file, skipped records in a file.
                   4965: 
1.489     albertel 4966:     $r->print('
                   4967:    <br />
                   4968:    <form action="/adm/grades" name="scantron_download">
                   4969:      '.$default_form_data.'
                   4970:      <input type="hidden" name="command" value="scantron_download" />
                   4971:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   4972:        '.&Apache::loncommon::start_data_table_header_row().'
                   4973:               <th>
1.492     albertel 4974:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 4975:               </th>
                   4976:        '.&Apache::loncommon::end_data_table_header_row().'
                   4977:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4978:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 4979:                 <br />
1.492     albertel 4980:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 4981:        '.&Apache::loncommon::end_data_table_row().'
                   4982:      '.&Apache::loncommon::end_data_table().'
                   4983:    </form>
                   4984:    <br />
                   4985: ');
1.162     albertel 4986: 
1.457     banghart 4987:     &Apache::lonpickcode::code_list($r,2);
                   4988:     $r->print($grading_menu_button);
1.162     albertel 4989:     return
1.75      albertel 4990: }
                   4991: 
1.423     albertel 4992: =pod
                   4993: 
                   4994: =item get_scantron_config
                   4995: 
                   4996:    Parse and return the scantron configuration line selected as a
                   4997:    hash of configuration file fields.
                   4998: 
                   4999:  Arguments:
                   5000:     which - the name of the configuration to parse from the file.
                   5001: 
                   5002: 
                   5003:  Returns:
                   5004:             If the named configuration is not in the file, an empty
                   5005:             hash is returned.
                   5006:     a hash with the fields
                   5007:       name         - internal name for the this configuration setup
                   5008:       description  - text to display to operator that describes this config
                   5009:       CODElocation - if 0 or the string 'none'
                   5010:                           - no CODE exists for this config
                   5011:                      if -1 || the string 'letter'
                   5012:                           - a CODE exists for this config and is
                   5013:                             a string of letters
                   5014:                      Unsupported value (but planned for future support)
                   5015:                           if a positive integer
                   5016:                                - The CODE exists as the first n items from
                   5017:                                  the question section of the form
                   5018:                           if the string 'number'
                   5019:                                - The CODE exists for this config and is
                   5020:                                  a string of numbers
                   5021:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5022:                      the CODE starts
                   5023:       CODElength  - length of the CODE
                   5024:       IDstart     - column where the student ID number starts
                   5025:       IDlength    - length of the student ID info
                   5026:       Qstart      - column where the information from the bubbled
                   5027:                     'questions' start
                   5028:       Qlength     - number of columns comprising a single bubble line from
                   5029:                     the sheet. (usually either 1 or 10)
1.424     albertel 5030:       Qon         - either a single character representing the character used
1.423     albertel 5031:                     to signal a bubble was chosen in the positional setup, or
                   5032:                     the string 'letter' if the letter of the chosen bubble is
                   5033:                     in the final, or 'number' if a number representing the
                   5034:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5035:       Qoff        - the character used to represent that a bubble was
                   5036:                     left blank
1.423     albertel 5037:       PaperID     - if the scanning process generates a unique number for each
                   5038:                     sheet scanned the column that this ID number starts in
                   5039:       PaperIDlength - number of columns that comprise the unique ID number
                   5040:                       for the sheet of paper
1.424     albertel 5041:       FirstName   - column that the first name starts in
1.423     albertel 5042:       FirstNameLength - number of columns that the first name spans
                   5043:  
                   5044:       LastName    - column that the last name starts in
                   5045:       LastNameLength - number of columns that the last name spans
                   5046: 
                   5047: =cut
1.422     foxr     5048: 
1.82      albertel 5049: sub get_scantron_config {
                   5050:     my ($which) = @_;
                   5051:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5052:     my %config;
1.157     albertel 5053:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 5054:     foreach my $line (<$fh>) {
                   5055: 	my ($name,$descrip)=split(/:/,$line);
                   5056: 	if ($name ne $which ) { next; }
                   5057: 	chomp($line);
                   5058: 	my @config=split(/:/,$line);
                   5059: 	$config{'name'}=$config[0];
                   5060: 	$config{'description'}=$config[1];
                   5061: 	$config{'CODElocation'}=$config[2];
                   5062: 	$config{'CODEstart'}=$config[3];
                   5063: 	$config{'CODElength'}=$config[4];
                   5064: 	$config{'IDstart'}=$config[5];
                   5065: 	$config{'IDlength'}=$config[6];
                   5066: 	$config{'Qstart'}=$config[7];
                   5067: 	$config{'Qlength'}=$config[8];
                   5068: 	$config{'Qoff'}=$config[9];
                   5069: 	$config{'Qon'}=$config[10];
1.157     albertel 5070: 	$config{'PaperID'}=$config[11];
                   5071: 	$config{'PaperIDlength'}=$config[12];
                   5072: 	$config{'FirstName'}=$config[13];
                   5073: 	$config{'FirstNamelength'}=$config[14];
                   5074: 	$config{'LastName'}=$config[15];
                   5075: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5076: 	last;
                   5077:     }
                   5078:     return %config;
                   5079: }
                   5080: 
1.423     albertel 5081: =pod 
                   5082: 
                   5083: =item username_to_idmap
                   5084: 
                   5085:     creates a hash keyed by student id with values of the corresponding
                   5086:     student username:domain.
                   5087: 
                   5088:   Arguments:
                   5089: 
                   5090:     $classlist - reference to the class list hash. This is a hash
                   5091:                  keyed by student name:domain  whose elements are references
1.424     albertel 5092:                  to arrays containing various chunks of information
1.423     albertel 5093:                  about the student. (See loncoursedata for more info).
                   5094: 
                   5095:   Returns
                   5096:     %idmap - the constructed hash
                   5097: 
                   5098: =cut
                   5099: 
1.82      albertel 5100: sub username_to_idmap {
                   5101:     my ($classlist)= @_;
                   5102:     my %idmap;
                   5103:     foreach my $student (keys(%$classlist)) {
                   5104: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5105: 	    $student;
                   5106:     }
                   5107:     return %idmap;
                   5108: }
1.423     albertel 5109: 
                   5110: =pod
                   5111: 
1.424     albertel 5112: =item scantron_fixup_scanline
1.423     albertel 5113: 
                   5114:    Process a requested correction to a scanline.
                   5115: 
                   5116:   Arguments:
                   5117:     $scantron_config   - hash from &get_scantron_config()
                   5118:     $scan_data         - hash of correction information 
                   5119:                           (see &scantron_getfile())
                   5120:     $line              - existing scanline
                   5121:     $whichline         - line number of the passed in scanline
                   5122:     $field             - type of change to process 
                   5123:                          (either 
                   5124:                           'ID'     -> correct the student ID number
                   5125:                           'CODE'   -> correct the CODE
                   5126:                           'answer' -> fixup the submitted answers)
                   5127:     
                   5128:    $args               - hash of additional info,
                   5129:                           - 'ID' 
                   5130:                                'newid' -> studentID to use in replacement
1.424     albertel 5131:                                           of existing one
1.423     albertel 5132:                           - 'CODE' 
                   5133:                                'CODE_ignore_dup' - set to true if duplicates
                   5134:                                                    should be ignored.
                   5135: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5136:                                         if the existing unfound code should
1.423     albertel 5137:                                         be used as is
                   5138:                           - 'answer'
                   5139:                                'response' - new answer or 'none' if blank
                   5140:                                'question' - the bubble line to change
                   5141: 
                   5142:   Returns:
                   5143:     $line - the modified scanline
                   5144: 
                   5145:   Side effects: 
                   5146:     $scan_data - may be updated
                   5147: 
                   5148: =cut
                   5149: 
1.82      albertel 5150: 
1.157     albertel 5151: sub scantron_fixup_scanline {
                   5152:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.479     foxr     5153:     
                   5154:     
1.157     albertel 5155:     if ($field eq 'ID') {
                   5156: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5157: 	    return ($line,1,'New value too large');
1.157     albertel 5158: 	}
                   5159: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5160: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5161: 				     $args->{'newid'});
                   5162: 	}
                   5163: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5164: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5165: 	if ($args->{'newid'}=~/^\s*$/) {
                   5166: 	    &scan_data($scan_data,"$whichline.user",
                   5167: 		       $args->{'username'}.':'.$args->{'domain'});
                   5168: 	}
1.186     albertel 5169:     } elsif ($field eq 'CODE') {
1.192     albertel 5170: 	if ($args->{'CODE_ignore_dup'}) {
                   5171: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5172: 	}
                   5173: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5174: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5175: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5176: 		return ($line,1,'New CODE value too large');
                   5177: 	    }
                   5178: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5179: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5180: 	    }
                   5181: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5182: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5183: 	}
1.157     albertel 5184:     } elsif ($field eq 'answer') {
1.479     foxr     5185: 	&scantron_get_maxbubble(); # Need the bubble counter info.
1.482     foxr     5186: 	my $length =$scantron_config->{'Qlength'};
1.157     albertel 5187: 	my $off=$scantron_config->{'Qoff'};
                   5188: 	my $on=$scantron_config->{'Qon'};
1.479     foxr     5189:         my $question_number = $args->{'question'} -1;
                   5190:         my $first_position  = $first_bubble_line{$question_number};
                   5191: 	my $bubble_count    = $bubble_lines_per_response{$question_number};
                   5192:         my $bubbles_per_line= $$scantron_config{'Qlength'};
1.482     foxr     5193: 	my $answer=${off}x($bubbles_per_line*$bubble_count);
1.479     foxr     5194:         my $final_answer;
                   5195:         if ($$scantron_config{'Qon'} eq 'letter'  ||
                   5196: 	    $$scantron_config{'Qon'} eq 'number') { 
                   5197: 	    $bubbles_per_line = 10;
                   5198: 	}
                   5199: 	if (defined $args->{'response'}) {
                   5200: 	    
                   5201: 	    if ($args->{'response'} eq 'none') {
                   5202: 		&scan_data($scan_data,
                   5203: 			   "$whichline.no_bubble.".$args->{'question'},'1');
1.274     albertel 5204: 	    } else {
1.479     foxr     5205: 		my ($bubble_line, $bubble_number) = split(/:/,$args->{'response'});
                   5206: 		if ($on eq 'letter') {
                   5207: 		    my @alphabet=('A'..'Z');
                   5208: 		    $answer=$alphabet[$bubble_number];
                   5209: 		} elsif ($on eq 'number') {
1.482     foxr     5210: 		    $answer= $bubble_number+1;
1.479     foxr     5211: 		    if ($answer == 10) { $answer = '0'; }
                   5212: 		} else {
1.482     foxr     5213: 		    substr($answer,$bubble_number+$bubble_line*$bubbles_per_line,1)=$on;
                   5214: 		    $final_answer = $answer;
1.479     foxr     5215: 		}
                   5216: 		&scan_data($scan_data,
                   5217: 			   "$whichline.no_bubble.".$args->{'question'},undef,'1');
1.482     foxr     5218: 		
                   5219: 		# Positional notation already has the right final answer length..
                   5220: 
                   5221: 		if (($on eq 'letter') || ($on eq 'number')) {
                   5222: 		    for (my $l = 0; $l < $bubble_count; $l++) {
                   5223: 			if ($l eq $bubble_line) {
                   5224: 			    $final_answer .= $answer;
                   5225: 			} else {
                   5226: 			    $final_answer .= ' ';
                   5227: 			}
1.479     foxr     5228: 		    }
                   5229: 		}
1.274     albertel 5230: 	    }
1.479     foxr     5231: 	    # $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5232: 	    #substr($line,$where-1,$length)=$answer;
                   5233: 	    substr($line, 
                   5234: 		   $scantron_config->{'Qstart'}+$first_position-1,
1.482     foxr     5235: 		   $bubbles_per_line*$length) = $final_answer;
1.157     albertel 5236: 	}
                   5237:     }
                   5238:     return $line;
                   5239: }
1.423     albertel 5240: 
                   5241: =pod
                   5242: 
                   5243: =item scan_data
                   5244: 
                   5245:     Edit or look up  an item in the scan_data hash.
                   5246: 
                   5247:   Arguments:
                   5248:     $scan_data  - The hash (see scantron_getfile)
                   5249:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5250:                   scantronfilename_key).
1.423     albertel 5251:     $data        - New value of the hash entry.
                   5252:     $delete      - If true, the entry is removed from the hash.
                   5253: 
                   5254:   Returns:
                   5255:     The new value of the hash table field (undefined if deleted).
                   5256: 
                   5257: =cut
                   5258: 
                   5259: 
1.157     albertel 5260: sub scan_data {
                   5261:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5262:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5263:     if (defined($value)) {
                   5264: 	$scan_data->{$filename.'_'.$key} = $value;
                   5265:     }
                   5266:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5267:     return $scan_data->{$filename.'_'.$key};
                   5268: }
1.423     albertel 5269: 
1.495   ! albertel 5270: # ----- These first few routines are general use routines.----
        !          5271: 
        !          5272: # Return the number of occurences of a pattern in a string.
        !          5273: 
        !          5274: sub occurence_count {
        !          5275:     my ($string, $pattern) = @_;
        !          5276: 
        !          5277:     my @matches = ($string =~ /$pattern/g);
        !          5278: 
        !          5279:     return scalar(@matches);
        !          5280: }
        !          5281: 
        !          5282: 
        !          5283: # Take a string known to have digits and convert all the
        !          5284: # digits into letters in the range J,A..I.
        !          5285: 
        !          5286: sub digits_to_letters {
        !          5287:     my ($input) = @_;
        !          5288: 
        !          5289:     my @alphabet = ('J', 'A'..'I');
        !          5290: 
        !          5291:     my @input    = split(//, $input);
        !          5292:     my $output ='';
        !          5293:     for (my $i = 0; $i < scalar(@input); $i++) {
        !          5294: 	if ($input[$i] =~ /\d/) {
        !          5295: 	    $output .= $alphabet[$input[$i]];
        !          5296: 	} else {
        !          5297: 	    $output .= $input[$i];
        !          5298: 	}
        !          5299:     }
        !          5300:     return $output;
        !          5301: }
        !          5302: 
1.423     albertel 5303: =pod 
                   5304: 
                   5305: =item scantron_parse_scanline
                   5306: 
                   5307:   Decodes a scanline from the selected scantron file
                   5308: 
                   5309:  Arguments:
                   5310:     line             - The text of the scantron file line to process
                   5311:     whichline        - Line number
                   5312:     scantron_config  - Hash describing the format of the scantron lines.
                   5313:     scan_data        - Hash of extra information about the scanline
                   5314:                        (see scantron_getfile for more information)
                   5315:     just_header      - True if should not process question answers but only
                   5316:                        the stuff to the left of the answers.
                   5317:  Returns:
                   5318:    Hash containing the result of parsing the scanline
                   5319: 
                   5320:    Keys are all proceeded by the string 'scantron.'
                   5321: 
                   5322:        CODE    - the CODE in use for this scanline
                   5323:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5324:                  by the operator
                   5325:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5326:                             CODEs were selected, but the usage has been
                   5327:                             forced by the operator
                   5328:        ID  - student ID
                   5329:        PaperID - if used, the ID number printed on the sheet when the 
                   5330:                  paper was scanned
                   5331:        FirstName - first name from the sheet
                   5332:        LastName  - last name from the sheet
                   5333: 
                   5334:      if just_header was not true these key may also exist
                   5335: 
1.447     foxr     5336:        missingerror - a list of bubble ranges that are considered to be answers
                   5337:                       to a single question that don't have any bubbles filled in.
                   5338:                       Of the form questionnumber:firstbubblenumber:count.
                   5339:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5340:                       to a single question that have more than one bubble filled in.
                   5341:                       Of the form questionnumber::firstbubblenumber:count
                   5342:    
                   5343:                 In the above, count is the number of bubble responses in the
                   5344:                 input line needed to represent the possible answers to the question.
                   5345:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5346:                 per line would have count = 2.
                   5347: 
1.423     albertel 5348:        maxquest     - the number of the last bubble line that was parsed
                   5349: 
                   5350:        (<number> starts at 1)
                   5351:        <number>.answer - zero or more letters representing the selected
                   5352:                          letters from the scanline for the bubble line 
                   5353:                          <number>.
                   5354:                          if blank there was either no bubble or there where
                   5355:                          multiple bubbles, (consult the keys missingerror and
                   5356:                          doubleerror if this is an error condition)
                   5357: 
                   5358: =cut
                   5359: 
1.82      albertel 5360: sub scantron_parse_scanline {
1.423     albertel 5361:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5362: 
1.82      albertel 5363:     my %record;
1.422     foxr     5364:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5365:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5366:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5367: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5368: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5369: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5370: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5371: 	    $record{'scantron.CODE'}=substr($data,
                   5372: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5373: 					    $$scantron_config{'CODElength'});
1.191     albertel 5374: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5375: 		$record{'scantron.useCODE'}=1;
                   5376: 	    }
1.192     albertel 5377: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5378: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5379: 	    }
1.82      albertel 5380: 	} else {
                   5381: 	    #FIXME interpret first N questions
                   5382: 	}
                   5383:     }
1.83      albertel 5384:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5385: 				  $$scantron_config{'IDlength'});
1.157     albertel 5386:     $record{'scantron.PaperID'}=
                   5387: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5388: 	       $$scantron_config{'PaperIDlength'});
                   5389:     $record{'scantron.FirstName'}=
                   5390: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5391: 	       $$scantron_config{'FirstNamelength'});
                   5392:     $record{'scantron.LastName'}=
                   5393: 	substr($data,$$scantron_config{'LastName'}-1,
                   5394: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5395:     if ($just_header) { return \%record; }
1.194     albertel 5396: 
1.82      albertel 5397:     my @alphabet=('A'..'Z');
                   5398:     my $questnum=0;
1.447     foxr     5399:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5400: 
1.470     foxr     5401:     chomp($questions);		# Get rid of any trailing \n.
                   5402:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5403:     while (length($questions)) {
1.447     foxr     5404: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.494     albertel 5405: 	my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5406: 	                     || 1;
1.447     foxr     5407: 
1.82      albertel 5408: 	$questnum++;
1.447     foxr     5409: 	my $currentquest = substr($questions,0,$answer_length);
1.490     foxr     5410: 	$questions       = substr($questions,$answer_length);
1.447     foxr     5411: 	if (length($currentquest) < $answer_length) { next; }
                   5412: 
                   5413: 	# Qon letter implies for each slot in currentquest we have:
                   5414: 	#    ? or * for doubles a letter in A-Z for a bubble and
                   5415:         #    about anything else (esp. a value of Qoff for missing
                   5416: 	#    bubbles.
                   5417: 
                   5418: 
1.239     albertel 5419: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.447     foxr     5420: 	    if ($currentquest =~ /\?/
                   5421: 		|| $currentquest =~ /\*/
                   5422: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
1.274     albertel 5423: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5424: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
1.460     foxr     5425: 		    my $bubble = substr($currentquest, $ans, 1);
                   5426: 		    if ($bubble =~ /[A-Z]/ ) {
                   5427: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5428: 		    } else {
                   5429: 			$record{"scantron.$ansnum.answer"}='';
                   5430: 		    }
1.447     foxr     5431: 		    $ansnum++;
                   5432: 		}
                   5433: 
1.389     albertel 5434: 	    } elsif (!defined($currentquest)
1.447     foxr     5435: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
                   5436: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
                   5437: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5438: 		    $record{"scantron.$ansnum.answer"}='';
                   5439: 		    $ansnum++;
                   5440: 
                   5441: 		}
1.239     albertel 5442: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5443: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.470     foxr     5444: 		   #  $ansnum += $answers_needed;
1.239     albertel 5445: 		}
                   5446: 	    } else {
1.447     foxr     5447: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
1.490     foxr     5448: 		    my $bubble = substr($currentquest, $ans, 1);
                   5449: 		    $record{"scantron.$ansnum.answer"} = $bubble;
1.447     foxr     5450: 		    $ansnum++;
                   5451: 		}
1.239     albertel 5452: 	    }
1.447     foxr     5453: 
                   5454: 	# Qon 'number' implies each slot gives a digit that indexes the
                   5455: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
                   5456:         #    and *? for double bubbles on a line.
                   5457: 	#    these answers are also stored as letters.
                   5458: 
1.239     albertel 5459: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.447     foxr     5460: 	    if ($currentquest =~ /\?/
                   5461: 		|| $currentquest =~ /\*/
                   5462: 		|| (&occurence_count($currentquest, '\d') > 1)) {
1.274     albertel 5463: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5464: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
1.460     foxr     5465: 		    my $bubble = substr($currentquest, $ans, 1);
                   5466: 		    if ($bubble =~ /\d/) {
                   5467: 			$record{"scantron.$ansnum.answer"} = $alphabet[$bubble];
                   5468: 		    } else {
1.461     foxr     5469: 			$record{"scantron.$ansnum.answer"}=' ';
1.460     foxr     5470: 		    }
1.447     foxr     5471: 		    $ansnum++;
                   5472: 		}
                   5473: 
1.389     albertel 5474: 	    } elsif (!defined($currentquest)
1.447     foxr     5475: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
                   5476: 		     || (&occurence_count($currentquest, '\d') == 0)) {
                   5477: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5478: 		    $record{"scantron.$ansnum.answer"}='';
                   5479: 		    $ansnum++;
                   5480: 
                   5481: 		}
1.239     albertel 5482: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5483: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5484: 		    $ansnum += $answers_needed;
1.239     albertel 5485: 		}
1.447     foxr     5486: 
1.239     albertel 5487: 	    } else {
1.447     foxr     5488: 		$currentquest = &digits_to_letters($currentquest);
                   5489: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5490: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5491: 		    $ansnum++;
1.371     albertel 5492: 		}
1.239     albertel 5493: 	    }
1.82      albertel 5494: 	} else {
1.447     foxr     5495: 
                   5496: 	    # Otherwise there's a positional notation;
                   5497: 	    # each bubble line requires Qlength items, and there are filled in
                   5498: 	    # bubbles for each case where there 'Qon' characters.
                   5499: 	    #
                   5500: 
1.239     albertel 5501: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
1.447     foxr     5502: 
                   5503: 	    # If the split only  giveas us one element.. the full length of the
                   5504: 	    # answser string, no bubbles are filled in:
                   5505: 
                   5506: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5507: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5508: 		    $record{"scantron.$ansnum.answer"}='';
                   5509: 		    $ansnum++;
                   5510: 
                   5511: 		}
1.239     albertel 5512: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5513: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5514: 		}
1.482     foxr     5515: 		
                   5516: 
1.490     foxr     5517: 
                   5518: 	    } elsif (scalar(@array) eq 2) {
1.447     foxr     5519: 
1.459     foxr     5520: 		my $location      = length($array[0]);
1.483     foxr     5521: 		my $line_num      = int($location / $$scantron_config{'Qlength'});
1.447     foxr     5522: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
1.483     foxr     5523: 		
1.447     foxr     5524: 
                   5525: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5526: 		    if ($ans eq $line_num) {
                   5527: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5528: 		    } else {
                   5529: 			$record{"scantron.$ansnum.answer"} = ' ';
                   5530: 		    }
                   5531: 		    $ansnum++;
                   5532: 		}
1.239     albertel 5533: 	    }
1.447     foxr     5534: 	    #  If there's more than one instance of a bubble character
                   5535: 	    #  That's a double bubble; with positional notation we can
                   5536: 	    #  record all the bubbles filled in as well as the 
                   5537: 	    #  fact this response consists of multiple bubbles.
                   5538: 	    #
                   5539: 	    else {
1.239     albertel 5540: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5541: 
                   5542: 		my $first_answer = $ansnum;
                   5543: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
1.462     foxr     5544: 		    my $item = $first_answer+$ans;
                   5545: 		    $record{"scantron.$item.answer"} = '';
1.447     foxr     5546: 		}
                   5547: 
1.239     albertel 5548: 		my @ans=@array;
1.462     foxr     5549: 		my $i=0;
                   5550: 		my $increment = 0;
1.239     albertel 5551: 		while ($#ans) {
1.462     foxr     5552: 		    $i+=length($ans[0]) + $increment;
                   5553: 		    my $line   = int($i/$$scantron_config{'Qlength'} + $first_answer);
1.447     foxr     5554: 		    my $bubble = $i%$$scantron_config{'Qlength'};
                   5555: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
1.239     albertel 5556: 		    shift(@ans);
1.462     foxr     5557: 		    $increment = 1;
1.239     albertel 5558: 		}
1.462     foxr     5559: 		$ansnum += $answers_needed;
1.239     albertel 5560: 	    }
1.82      albertel 5561: 	}
                   5562:     }
1.83      albertel 5563:     $record{'scantron.maxquest'}=$questnum;
                   5564:     return \%record;
1.82      albertel 5565: }
                   5566: 
1.423     albertel 5567: =pod
                   5568: 
                   5569: =item scantron_add_delay
                   5570: 
                   5571:    Adds an error message that occurred during the grading phase to a
                   5572:    queue of messages to be shown after grading pass is complete
                   5573: 
                   5574:  Arguments:
1.424     albertel 5575:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5576:    $scanline    - the scanline that caused the error
                   5577:    $errormesage - the error message
                   5578:    $errorcode   - a numeric code for the error
                   5579: 
                   5580:  Side Effects:
1.424     albertel 5581:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5582: 
                   5583: =cut
                   5584: 
1.82      albertel 5585: sub scantron_add_delay {
1.140     albertel 5586:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5587:     push(@$delayqueue,
                   5588: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5589: 	  'ecode' => $errorcode }
                   5590: 	 );
1.82      albertel 5591: }
                   5592: 
1.423     albertel 5593: =pod
                   5594: 
                   5595: =item scantron_find_student
                   5596: 
1.424     albertel 5597:    Finds the username for the current scanline
                   5598: 
                   5599:   Arguments:
                   5600:    $scantron_record - hash result from scantron_parse_scanline
                   5601:    $scan_data       - hash of correction information 
                   5602:                       (see &scantron_getfile() form more information)
                   5603:    $idmap           - hash from &username_to_idmap()
                   5604:    $line            - number of current scanline
                   5605:  
                   5606:   Returns:
                   5607:    Either 'username:domain' or undef if unknown
                   5608: 
1.423     albertel 5609: =cut
                   5610: 
1.82      albertel 5611: sub scantron_find_student {
1.157     albertel 5612:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5613:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5614:     if ($scanID =~ /^\s*$/) {
                   5615:  	return &scan_data($scan_data,"$line.user");
                   5616:     }
1.83      albertel 5617:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5618:  	if (lc($id) eq lc($scanID)) {
                   5619:  	    return $$idmap{$id};
                   5620:  	}
1.83      albertel 5621:     }
                   5622:     return undef;
                   5623: }
                   5624: 
1.423     albertel 5625: =pod
                   5626: 
                   5627: =item scantron_filter
                   5628: 
1.424     albertel 5629:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5630:    hidden resources was selected
                   5631: 
1.423     albertel 5632: =cut
                   5633: 
1.83      albertel 5634: sub scantron_filter {
                   5635:     my ($curres)=@_;
1.331     albertel 5636: 
                   5637:     if (ref($curres) && $curres->is_problem()) {
                   5638: 	# if the user has asked to not have either hidden
                   5639: 	# or 'randomout' controlled resources to be graded
                   5640: 	# don't include them
                   5641: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5642: 	    && $curres->randomout) {
                   5643: 	    return 0;
                   5644: 	}
1.83      albertel 5645: 	return 1;
                   5646:     }
                   5647:     return 0;
1.82      albertel 5648: }
                   5649: 
1.423     albertel 5650: =pod
                   5651: 
                   5652: =item scantron_process_corrections
                   5653: 
1.424     albertel 5654:    Gets correction information out of submitted form data and corrects
                   5655:    the scanline
                   5656: 
1.423     albertel 5657: =cut
                   5658: 
1.157     albertel 5659: sub scantron_process_corrections {
                   5660:     my ($r) = @_;
1.257     albertel 5661:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5662:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5663:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5664:     my $which=$env{'form.scantron_line'};
1.200     albertel 5665:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5666:     my ($skip,$err,$errmsg);
1.257     albertel 5667:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5668: 	$skip=1;
1.257     albertel 5669:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5670: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5671: 	    $env{'form.scantron_domain'};
1.157     albertel 5672: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5673: 	($line,$err,$errmsg)=
                   5674: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5675: 				     'ID',{'newid'=>$newid,
1.257     albertel 5676: 				    'username'=>$env{'form.scantron_username'},
                   5677: 				    'domain'=>$env{'form.scantron_domain'}});
                   5678:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5679: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5680: 	my $newCODE;
1.192     albertel 5681: 	my %args;
1.190     albertel 5682: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5683: 	    $newCODE='use_unfound';
1.190     albertel 5684: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5685: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5686: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5687: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5688: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5689: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5690: 	}
1.257     albertel 5691: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5692: 	    $args{'CODE_ignore_dup'}=1;
                   5693: 	}
                   5694: 	$args{'CODE'}=$newCODE;
1.186     albertel 5695: 	($line,$err,$errmsg)=
                   5696: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5697: 				     'CODE',\%args);
1.257     albertel 5698:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5699: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5700: 	    ($line,$err,$errmsg)=
                   5701: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5702: 					 $which,'answer',
                   5703: 					 { 'question'=>$question,
1.257     albertel 5704: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5705: 	    if ($err) { last; }
                   5706: 	}
                   5707:     }
                   5708:     if ($err) {
1.398     albertel 5709: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5710:     } else {
1.200     albertel 5711: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5712: 	&scantron_putfile($scanlines,$scan_data);
                   5713:     }
                   5714: }
                   5715: 
1.423     albertel 5716: =pod
                   5717: 
                   5718: =item reset_skipping_status
                   5719: 
1.424     albertel 5720:    Forgets the current set of remember skipped scanlines (and thus
                   5721:    reverts back to considering all lines in the
                   5722:    scantron_skipped_<filename> file)
                   5723: 
1.423     albertel 5724: =cut
                   5725: 
1.200     albertel 5726: sub reset_skipping_status {
                   5727:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5728:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5729:     &scantron_putfile(undef,$scan_data);
                   5730: }
                   5731: 
1.423     albertel 5732: =pod
                   5733: 
                   5734: =item start_skipping
                   5735: 
1.424     albertel 5736:    Marks a scanline to be skipped. 
                   5737: 
1.423     albertel 5738: =cut
                   5739: 
1.376     albertel 5740: sub start_skipping {
1.200     albertel 5741:     my ($scan_data,$i)=@_;
                   5742:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5743:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5744: 	$remembered{$i}=2;
                   5745:     } else {
                   5746: 	$remembered{$i}=1;
                   5747:     }
1.200     albertel 5748:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5749: }
                   5750: 
1.423     albertel 5751: =pod
                   5752: 
                   5753: =item should_be_skipped
                   5754: 
1.424     albertel 5755:    Checks whether a scanline should be skipped.
                   5756: 
1.423     albertel 5757: =cut
                   5758: 
1.200     albertel 5759: sub should_be_skipped {
1.376     albertel 5760:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5761:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5762: 	# not redoing old skips
1.376     albertel 5763: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5764: 	return 0;
                   5765:     }
                   5766:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5767: 
                   5768:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5769: 	return 0;
                   5770:     }
1.200     albertel 5771:     return 1;
                   5772: }
                   5773: 
1.423     albertel 5774: =pod
                   5775: 
                   5776: =item remember_current_skipped
                   5777: 
1.424     albertel 5778:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5779:    file and remembers them into scan_data for later use.
                   5780: 
1.423     albertel 5781: =cut
                   5782: 
1.200     albertel 5783: sub remember_current_skipped {
                   5784:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5785:     my %to_remember;
                   5786:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5787: 	if ($scanlines->{'skipped'}[$i]) {
                   5788: 	    $to_remember{$i}=1;
                   5789: 	}
                   5790:     }
1.376     albertel 5791: 
1.200     albertel 5792:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5793:     &scantron_putfile(undef,$scan_data);
                   5794: }
                   5795: 
1.423     albertel 5796: =pod
                   5797: 
                   5798: =item check_for_error
                   5799: 
1.424     albertel 5800:     Checks if there was an error when attempting to remove a specific
                   5801:     scantron_.. bubble sheet data file. Prints out an error if
                   5802:     something went wrong.
                   5803: 
1.423     albertel 5804: =cut
                   5805: 
1.200     albertel 5806: sub check_for_error {
                   5807:     my ($r,$result)=@_;
                   5808:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 5809: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 5810:     }
                   5811: }
1.157     albertel 5812: 
1.423     albertel 5813: =pod
                   5814: 
                   5815: =item scantron_warning_screen
                   5816: 
1.424     albertel 5817:    Interstitial screen to make sure the operator has selected the
                   5818:    correct options before we start the validation phase.
                   5819: 
1.423     albertel 5820: =cut
                   5821: 
1.203     albertel 5822: sub scantron_warning_screen {
                   5823:     my ($button_text)=@_;
1.257     albertel 5824:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5825:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5826:     my $CODElist;
1.284     albertel 5827:     if ($scantron_config{'CODElocation'} &&
                   5828: 	$scantron_config{'CODEstart'} &&
                   5829: 	$scantron_config{'CODElength'}) {
                   5830: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5831: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5832: 	$CODElist=
1.492     albertel 5833: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 5834: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5835:     }
1.492     albertel 5836:     return ('
1.203     albertel 5837: <p>
1.492     albertel 5838: <span class="LC_warning">
                   5839: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 5840: </p>
                   5841: <table>
1.492     albertel 5842: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   5843: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   5844: '.$CODElist.'
1.203     albertel 5845: </table>
                   5846: <br />
1.492     albertel 5847: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   5848: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 5849: 
                   5850: <br />
1.492     albertel 5851: ');
1.203     albertel 5852: }
                   5853: 
1.423     albertel 5854: =pod
                   5855: 
                   5856: =item scantron_do_warning
                   5857: 
1.424     albertel 5858:    Check if the operator has picked something for all required
                   5859:    fields. Error out if something is missing.
                   5860: 
1.423     albertel 5861: =cut
                   5862: 
1.203     albertel 5863: sub scantron_do_warning {
                   5864:     my ($r)=@_;
1.324     albertel 5865:     my ($symb)=&get_symb($r);
1.203     albertel 5866:     if (!$symb) {return '';}
1.324     albertel 5867:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5868:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5869:     if ( $env{'form.selectpage'} eq '' ||
                   5870: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5871: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 5872: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 5873: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 5874: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 5875: 	} 
1.257     albertel 5876: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 5877: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
1.237     albertel 5878: 	} 
1.257     albertel 5879: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 5880: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
1.237     albertel 5881: 	} 
                   5882:     } else {
1.265     www      5883: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 5884: 	$r->print('
                   5885: '.$warning.'
                   5886: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 5887: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 5888: ');
1.237     albertel 5889:     }
1.352     albertel 5890:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5891:     return '';
                   5892: }
                   5893: 
1.423     albertel 5894: =pod
                   5895: 
                   5896: =item scantron_form_start
                   5897: 
1.424     albertel 5898:     html hidden input for remembering all selected grading options
                   5899: 
1.423     albertel 5900: =cut
                   5901: 
1.203     albertel 5902: sub scantron_form_start {
                   5903:     my ($max_bubble)=@_;
                   5904:     my $result= <<SCANTRONFORM;
                   5905: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5906:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5907:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5908:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5909:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5910:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5911:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5912:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5913:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5914:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5915: SCANTRONFORM
1.447     foxr     5916: 
                   5917:   my $line = 0;
                   5918:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   5919:        my $chunk =
                   5920: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     5921:        $chunk .=
                   5922: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.447     foxr     5923:        $result .= $chunk;
                   5924:        $line++;
                   5925:    }
1.203     albertel 5926:     return $result;
                   5927: }
                   5928: 
1.423     albertel 5929: =pod
                   5930: 
                   5931: =item scantron_validate_file
                   5932: 
1.424     albertel 5933:     Dispatch routine for doing validation of a bubble sheet data file.
                   5934: 
                   5935:     Also processes any necessary information resets that need to
                   5936:     occur before validation begins (ignore previous corrections,
                   5937:     restarting the skipped records processing)
                   5938: 
1.423     albertel 5939: =cut
                   5940: 
1.157     albertel 5941: sub scantron_validate_file {
                   5942:     my ($r) = @_;
1.324     albertel 5943:     my ($symb)=&get_symb($r);
1.157     albertel 5944:     if (!$symb) {return '';}
1.324     albertel 5945:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5946:     
                   5947:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5948:     # them when doing the corrections reset
1.257     albertel 5949:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5950: 	&reset_skipping_status();
                   5951:     }
1.257     albertel 5952:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5953: 	&remember_current_skipped();
1.257     albertel 5954: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5955:     }
                   5956: 
1.257     albertel 5957:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5958: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5959: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5960: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5961: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5962:     }
1.200     albertel 5963: 
1.257     albertel 5964:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5965: 	&scantron_process_corrections($r);
                   5966:     }
1.492     albertel 5967:     $r->print('<p>'.&mt('Gathering necessary info.').'</p>');$r->rflush();
1.157     albertel 5968:     #get the student pick code ready
                   5969:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5970:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5971:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5972:     $r->print($result);
                   5973:     
1.334     albertel 5974:     my @validate_phases=( 'sequence',
                   5975: 			  'ID',
1.157     albertel 5976: 			  'CODE',
                   5977: 			  'doublebubble',
                   5978: 			  'missingbubbles');
1.257     albertel 5979:     if (!$env{'form.validatepass'}) {
                   5980: 	$env{'form.validatepass'} = 0;
1.157     albertel 5981:     }
1.257     albertel 5982:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5983: 
1.448     foxr     5984: 
1.157     albertel 5985:     my $stop=0;
                   5986:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.492     albertel 5987: 	$r->print('<p> '.&mt('Validating '.$validate_phases[$currentphase]).'</p>');
1.157     albertel 5988: 	$r->rflush();
                   5989: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5990: 	{
                   5991: 	    no strict 'refs';
                   5992: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5993: 	}
                   5994:     }
                   5995:     if (!$stop) {
1.203     albertel 5996: 	my $warning=&scantron_warning_screen('Start Grading');
1.492     albertel 5997: 	$r->print('
                   5998: '.&mt('Validation process complete.').'<br />
                   5999: '.$warning.'
                   6000: <input type="submit" name="submit" value="'.&mt('Start Grading').'" />
1.203     albertel 6001: <input type="hidden" name="command" value="scantron_process" />
1.492     albertel 6002: ');
1.203     albertel 6003: 
1.157     albertel 6004:     } else {
                   6005: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6006: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6007:     }
                   6008:     if ($stop) {
1.334     albertel 6009: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.492     albertel 6010: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore -&gt;').' " />');
                   6011: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6012: 
1.492     albertel 6013: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6014: 	} else {
1.492     albertel 6015: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Continue -&gt;').'" />');
                   6016: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6017: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6018: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6019: 	}
1.157     albertel 6020:     }
1.352     albertel 6021:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6022:     return '';
                   6023: }
                   6024: 
1.423     albertel 6025: 
                   6026: =pod
                   6027: 
                   6028: =item scantron_remove_file
                   6029: 
1.424     albertel 6030:    Removes the requested bubble sheet data file, makes sure that
                   6031:    scantron_original_<filename> is never removed
                   6032: 
                   6033: 
1.423     albertel 6034: =cut
                   6035: 
1.200     albertel 6036: sub scantron_remove_file {
1.192     albertel 6037:     my ($which)=@_;
1.257     albertel 6038:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6039:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6040:     my $file='scantron_';
1.200     albertel 6041:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6042: 	$file.=$which.'_';
1.192     albertel 6043:     } else {
                   6044: 	return 'refused';
                   6045:     }
1.257     albertel 6046:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6047:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6048: }
                   6049: 
1.423     albertel 6050: 
                   6051: =pod
                   6052: 
                   6053: =item scantron_remove_scan_data
                   6054: 
1.424     albertel 6055:    Removes all scan_data correction for the requested bubble sheet
                   6056:    data file.  (In the case that both the are doing skipped records we need
                   6057:    to remember the old skipped lines for the time being so that element
                   6058:    persists for a while.)
                   6059: 
1.423     albertel 6060: =cut
                   6061: 
1.200     albertel 6062: sub scantron_remove_scan_data {
1.257     albertel 6063:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6064:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6065:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6066:     my @todelete;
1.257     albertel 6067:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6068:     foreach my $key (@keys) {
                   6069: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6070: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6071: 		$key=~/remember_skipping/) {
                   6072: 		next;
                   6073: 	    }
1.192     albertel 6074: 	    push(@todelete,$key);
                   6075: 	}
                   6076:     }
1.200     albertel 6077:     my $result;
1.192     albertel 6078:     if (@todelete) {
1.491     albertel 6079: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6080: 				       \@todelete,$cdom,$cname);
                   6081:     } else {
                   6082: 	$result = 'ok';
1.192     albertel 6083:     }
                   6084:     return $result;
                   6085: }
                   6086: 
1.423     albertel 6087: 
                   6088: =pod
                   6089: 
                   6090: =item scantron_getfile
                   6091: 
1.424     albertel 6092:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6093:     the scan_data hash
                   6094:   
                   6095:   Arguments:
                   6096:     None
                   6097: 
                   6098:   Returns:
                   6099:     2 hash references
                   6100: 
                   6101:      - first one has 
                   6102:          orig      -
                   6103:          corrected -
                   6104:          skipped   -  each of which points to an array ref of the specified
                   6105:                       file broken up into individual lines
                   6106:          count     - number of scanlines
                   6107:  
                   6108:      - second is the scan_data hash possible keys are
1.425     albertel 6109:        ($number refers to scanline numbered $number and thus the key affects
                   6110:         only that scanline
                   6111:         $bubline refers to the specific bubble line element and the aspects
                   6112:         refers to that specific bubble line element)
                   6113: 
                   6114:        $number.user - username:domain to use
                   6115:        $number.CODE_ignore_dup 
                   6116:                     - ignore the duplicate CODE error 
                   6117:        $number.useCODE
                   6118:                     - use the CODE in the scanline as is
                   6119:        $number.no_bubble.$bubline
                   6120:                     - it is valid that there is no bubbled in bubble
                   6121:                       at $number $bubline
                   6122:        remember_skipping
                   6123:                     - a frozen hash containing keys of $number and values
                   6124:                       of either 
                   6125:                         1 - we are on a 'do skipped records pass' and plan
                   6126:                             on processing this line
                   6127:                         2 - we are on a 'do skipped records pass' and this
                   6128:                             scanline has been marked to skip yet again
1.424     albertel 6129: 
1.423     albertel 6130: =cut
                   6131: 
1.157     albertel 6132: sub scantron_getfile {
1.200     albertel 6133:     #FIXME really would prefer a scantron directory
1.257     albertel 6134:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6135:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6136:     my $lines;
                   6137:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6138: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6139:     my %scanlines;
                   6140:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6141:     my $temp=$scanlines{'orig'};
                   6142:     $scanlines{'count'}=$#$temp;
                   6143: 
                   6144:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6145: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6146:     if ($lines eq '-1') {
                   6147: 	$scanlines{'corrected'}=[];
                   6148:     } else {
                   6149: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6150:     }
                   6151:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6152: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6153:     if ($lines eq '-1') {
                   6154: 	$scanlines{'skipped'}=[];
                   6155:     } else {
                   6156: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6157:     }
1.175     albertel 6158:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6159:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6160:     my %scan_data = @tmp;
                   6161:     return (\%scanlines,\%scan_data);
                   6162: }
                   6163: 
1.423     albertel 6164: =pod
                   6165: 
                   6166: =item lonnet_putfile
                   6167: 
1.424     albertel 6168:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6169: 
                   6170:  Arguments:
                   6171:    $contents - data to store
                   6172:    $filename - filename to store $contents into
                   6173: 
                   6174:  Returns:
                   6175:    result value from &Apache::lonnet::finishuserfileupload
                   6176: 
1.423     albertel 6177: =cut
                   6178: 
1.157     albertel 6179: sub lonnet_putfile {
                   6180:     my ($contents,$filename)=@_;
1.257     albertel 6181:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6182:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6183:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6184:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6185: 
                   6186: }
                   6187: 
1.423     albertel 6188: =pod
                   6189: 
                   6190: =item scantron_putfile
                   6191: 
1.424     albertel 6192:     Stores the current version of the bubble sheet data files, and the
                   6193:     scan_data hash. (Does not modify the original version only the
                   6194:     corrected and skipped versions.
                   6195: 
                   6196:  Arguments:
                   6197:     $scanlines - hash ref that looks like the first return value from
                   6198:                  &scantron_getfile()
                   6199:     $scan_data - hash ref that looks like the second return value from
                   6200:                  &scantron_getfile()
                   6201: 
1.423     albertel 6202: =cut
                   6203: 
1.157     albertel 6204: sub scantron_putfile {
                   6205:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6206:     #FIXME really would prefer a scantron directory
1.257     albertel 6207:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6208:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6209:     if ($scanlines) {
                   6210: 	my $prefix='scantron_';
1.157     albertel 6211: # no need to update orig, shouldn't change
                   6212: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6213: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6214: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6215: 			$prefix.'corrected_'.
1.257     albertel 6216: 			$env{'form.scantron_selectfile'});
1.200     albertel 6217: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6218: 			$prefix.'skipped_'.
1.257     albertel 6219: 			$env{'form.scantron_selectfile'});
1.200     albertel 6220:     }
1.175     albertel 6221:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6222: }
                   6223: 
1.423     albertel 6224: =pod
                   6225: 
                   6226: =item scantron_get_line
                   6227: 
1.424     albertel 6228:    Returns the correct version of the scanline
                   6229: 
                   6230:  Arguments:
                   6231:     $scanlines - hash ref that looks like the first return value from
                   6232:                  &scantron_getfile()
                   6233:     $scan_data - hash ref that looks like the second return value from
                   6234:                  &scantron_getfile()
                   6235:     $i         - number of the requested line (starts at 0)
                   6236: 
                   6237:  Returns:
                   6238:    A scanline, (either the original or the corrected one if it
                   6239:    exists), or undef if the requested scanline should be
                   6240:    skipped. (Either because it's an skipped scanline, or it's an
                   6241:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6242:    pass.
                   6243: 
1.423     albertel 6244: =cut
                   6245: 
1.157     albertel 6246: sub scantron_get_line {
1.200     albertel 6247:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6248:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6249:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6250:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6251:     return $scanlines->{'orig'}[$i]; 
                   6252: }
                   6253: 
1.423     albertel 6254: =pod
                   6255: 
                   6256: =item scantron_todo_count
                   6257: 
1.424     albertel 6258:     Counts the number of scanlines that need processing.
                   6259: 
                   6260:  Arguments:
                   6261:     $scanlines - hash ref that looks like the first return value from
                   6262:                  &scantron_getfile()
                   6263:     $scan_data - hash ref that looks like the second return value from
                   6264:                  &scantron_getfile()
                   6265: 
                   6266:  Returns:
                   6267:     $count - number of scanlines to process
                   6268: 
1.423     albertel 6269: =cut
                   6270: 
1.200     albertel 6271: sub get_todo_count {
                   6272:     my ($scanlines,$scan_data)=@_;
                   6273:     my $count=0;
                   6274:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6275: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6276: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6277: 	$count++;
                   6278:     }
                   6279:     return $count;
                   6280: }
                   6281: 
1.423     albertel 6282: =pod
                   6283: 
                   6284: =item scantron_put_line
                   6285: 
1.424     albertel 6286:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6287:     data file.
                   6288: 
                   6289:  Arguments:
                   6290:     $scanlines - hash ref that looks like the first return value from
                   6291:                  &scantron_getfile()
                   6292:     $scan_data - hash ref that looks like the second return value from
                   6293:                  &scantron_getfile()
                   6294:     $i         - line number to update
                   6295:     $newline   - contents of the updated scanline
                   6296:     $skip      - if true make the line for skipping and update the
                   6297:                  'skipped' file
                   6298: 
1.423     albertel 6299: =cut
                   6300: 
1.157     albertel 6301: sub scantron_put_line {
1.200     albertel 6302:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6303:     if ($skip) {
                   6304: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6305: 	&start_skipping($scan_data,$i);
1.157     albertel 6306: 	return;
                   6307:     }
                   6308:     $scanlines->{'corrected'}[$i]=$newline;
                   6309: }
                   6310: 
1.423     albertel 6311: =pod
                   6312: 
                   6313: =item scantron_clear_skip
                   6314: 
1.424     albertel 6315:    Remove a line from the 'skipped' file
                   6316: 
                   6317:  Arguments:
                   6318:     $scanlines - hash ref that looks like the first return value from
                   6319:                  &scantron_getfile()
                   6320:     $scan_data - hash ref that looks like the second return value from
                   6321:                  &scantron_getfile()
                   6322:     $i         - line number to update
                   6323: 
1.423     albertel 6324: =cut
                   6325: 
1.376     albertel 6326: sub scantron_clear_skip {
                   6327:     my ($scanlines,$scan_data,$i)=@_;
                   6328:     if (exists($scanlines->{'skipped'}[$i])) {
                   6329: 	undef($scanlines->{'skipped'}[$i]);
                   6330: 	return 1;
                   6331:     }
                   6332:     return 0;
                   6333: }
                   6334: 
1.423     albertel 6335: =pod
                   6336: 
                   6337: =item scantron_filter_not_exam
                   6338: 
1.424     albertel 6339:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6340:    filter out resources that are not marked as 'exam' mode
                   6341: 
1.423     albertel 6342: =cut
                   6343: 
1.334     albertel 6344: sub scantron_filter_not_exam {
                   6345:     my ($curres)=@_;
                   6346:     
                   6347:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6348: 	# if the user has asked to not have either hidden
                   6349: 	# or 'randomout' controlled resources to be graded
                   6350: 	# don't include them
                   6351: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6352: 	    && $curres->randomout) {
                   6353: 	    return 0;
                   6354: 	}
                   6355: 	return 1;
                   6356:     }
                   6357:     return 0;
                   6358: }
                   6359: 
1.423     albertel 6360: =pod
                   6361: 
                   6362: =item scantron_validate_sequence
                   6363: 
1.424     albertel 6364:     Validates the selected sequence, checking for resource that are
                   6365:     not set to exam mode.
                   6366: 
1.423     albertel 6367: =cut
                   6368: 
1.334     albertel 6369: sub scantron_validate_sequence {
                   6370:     my ($r,$currentphase) = @_;
                   6371: 
                   6372:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6373:     my (undef,undef,$sequence)=
                   6374: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6375: 
                   6376:     my $map=$navmap->getResourceByUrl($sequence);
                   6377: 
                   6378:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6379:                                     value="ignore" />');
                   6380:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6381: 	my @resources=
                   6382: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6383: 	if (@resources) {
1.357     banghart 6384: 	    $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 6385: 	    return (1,$currentphase);
                   6386: 	}
                   6387:     }
                   6388: 
                   6389:     return (0,$currentphase+1);
                   6390: }
                   6391: 
1.423     albertel 6392: =pod
                   6393: 
                   6394: =item scantron_validate_ID
                   6395: 
1.424     albertel 6396:    Validates all scanlines in the selected file to not have any
                   6397:    invalid or underspecified student IDs
                   6398: 
1.423     albertel 6399: =cut
                   6400: 
1.157     albertel 6401: sub scantron_validate_ID {
                   6402:     my ($r,$currentphase) = @_;
                   6403:     
                   6404:     #get student info
                   6405:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6406:     my %idmap=&username_to_idmap($classlist);
                   6407: 
                   6408:     #get scantron line setup
1.257     albertel 6409:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6410:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6411:     
                   6412:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6413: 
                   6414:     my %found=('ids'=>{},'usernames'=>{});
                   6415:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6416: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6417: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6418: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6419: 						 $scan_data);
                   6420: 	my $id=$$scan_record{'scantron.ID'};
                   6421: 	my $found;
                   6422: 	foreach my $checkid (keys(%idmap)) {
                   6423: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6424: 	}
                   6425: 	if ($found) {
                   6426: 	    my $username=$idmap{$found};
                   6427: 	    if ($found{'ids'}{$found}) {
                   6428: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6429: 					 $line,'duplicateID',$found);
1.194     albertel 6430: 		return(1,$currentphase);
1.157     albertel 6431: 	    } elsif ($found{'usernames'}{$username}) {
                   6432: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6433: 					 $line,'duplicateID',$username);
1.194     albertel 6434: 		return(1,$currentphase);
1.157     albertel 6435: 	    }
1.186     albertel 6436: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6437: 	    $found{'ids'}{$found}++;
                   6438: 	    $found{'usernames'}{$username}++;
                   6439: 	} else {
                   6440: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6441: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6442: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6443: 		    &scantron_get_correction($r,$i,$scan_record,
                   6444: 					     \%scantron_config,
                   6445: 					     $line,'duplicateID',$username);
1.194     albertel 6446: 		    return(1,$currentphase);
1.157     albertel 6447: 		} elsif (!defined($username)) {
                   6448: 		    &scantron_get_correction($r,$i,$scan_record,
                   6449: 					     \%scantron_config,
                   6450: 					     $line,'incorrectID');
1.194     albertel 6451: 		    return(1,$currentphase);
1.157     albertel 6452: 		}
                   6453: 		$found{'usernames'}{$username}++;
                   6454: 	    } else {
                   6455: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6456: 					 $line,'incorrectID');
1.194     albertel 6457: 		return(1,$currentphase);
1.157     albertel 6458: 	    }
                   6459: 	}
                   6460:     }
                   6461: 
                   6462:     return (0,$currentphase+1);
                   6463: }
                   6464: 
1.423     albertel 6465: =pod
                   6466: 
                   6467: =item scantron_get_correction
                   6468: 
1.424     albertel 6469:    Builds the interface screen to interact with the operator to fix a
                   6470:    specific error condition in a specific scanline
                   6471: 
                   6472:  Arguments:
                   6473:     $r           - Apache request object
                   6474:     $i           - number of the current scanline
                   6475:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6476:     $scan_config - hash ref as returned from &get_scantron_config()
                   6477:     $line        - full contents of the current scanline
                   6478:     $error       - error condition, valid values are
                   6479:                    'incorrectCODE', 'duplicateCODE',
                   6480:                    'doublebubble', 'missingbubble',
                   6481:                    'duplicateID', 'incorrectID'
                   6482:     $arg         - extra information needed
                   6483:        For errors:
                   6484:          - duplicateID   - paper number that this studentID was seen before on
                   6485:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6486:                            seen on before
                   6487:          - incorrectCODE - current incorrect CODE 
                   6488:          - doublebubble  - array ref of the bubble lines that have double
                   6489:                            bubble errors
                   6490:          - missingbubble - array ref of the bubble lines that have missing
                   6491:                            bubble errors
                   6492: 
1.423     albertel 6493: =cut
                   6494: 
1.157     albertel 6495: sub scantron_get_correction {
                   6496:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6497: 
1.454     banghart 6498: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6499: #to show both the current line and the previous one and allow skipping
                   6500: #the previous one or the current one
                   6501: 
1.333     albertel 6502:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6503: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6504: 			    " for PaperID <tt>[_1]</tt>",
                   6505: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6506:     } else {
1.492     albertel 6507: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6508: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6509: 			    $i,$line)."</p> \n");
                   6510:     }
                   6511:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6512: 			  "The name on the paper is [_2],[_3]",
                   6513: 			  $$scan_record{'scantron.ID'},
                   6514: 			  $$scan_record{'scantron.LastName'},
                   6515: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6516: 
1.157     albertel 6517:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6518:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6519:     if ($error =~ /ID$/) {
1.186     albertel 6520: 	if ($error eq 'incorrectID') {
1.492     albertel 6521: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6522: 		      "</p>\n");
1.157     albertel 6523: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6524: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6525: 	}
1.242     albertel 6526: 	$r->print($message);
1.492     albertel 6527: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6528: 	$r->print("\n<ul><li> ");
                   6529: 	#FIXME it would be nice if this sent back the user ID and
                   6530: 	#could do partial userID matches
                   6531: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6532: 				       'scantron_username','scantron_domain'));
                   6533: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6534: 	$r->print("\n@".
1.257     albertel 6535: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6536: 
                   6537: 	$r->print('</li>');
1.186     albertel 6538:     } elsif ($error =~ /CODE$/) {
                   6539: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6540: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6541: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6542: 	    $r->print("<p>".&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
1.186     albertel 6543: 	}
1.492     albertel 6544: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6545: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6546: 	$r->print($message);
1.492     albertel 6547: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6548: 	$r->print("\n<br /> ");
1.194     albertel 6549: 	my $i=0;
1.273     albertel 6550: 	if ($error eq 'incorrectCODE' 
                   6551: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6552: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6553: 	    if ($closest > 0) {
                   6554: 		foreach my $testcode (@{$closest}) {
                   6555: 		    my $checked='';
1.401     albertel 6556: 		    if (!$i) { $checked=' checked="checked" '; }
1.492     albertel 6557: 		    $r->print("
                   6558:    <label>
                   6559:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
                   6560:        ".&mt("Use the similar CODE [_1] instead.",
                   6561: 	    "<b><tt>".$testcode."</tt></b>")."
                   6562:     </label>
                   6563:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6564: 		    $r->print("\n<br />");
                   6565: 		    $i++;
                   6566: 		}
1.194     albertel 6567: 	    }
                   6568: 	}
1.273     albertel 6569: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6570: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.492     albertel 6571: 	    $r->print("
                   6572:     <label>
                   6573:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
                   6574:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6575: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6576:     </label>");
1.273     albertel 6577: 	    $r->print("\n<br />");
                   6578: 	}
1.194     albertel 6579: 
1.188     albertel 6580: 	$r->print(<<ENDSCRIPT);
                   6581: <script type="text/javascript">
                   6582: function change_radio(field) {
1.190     albertel 6583:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6584:     var i;
                   6585:     for (i=0;i<slct.length;i++) {
                   6586:         if (slct[i].value==field) { slct[i].checked=true; }
                   6587:     }
                   6588: }
                   6589: </script>
                   6590: ENDSCRIPT
1.187     albertel 6591: 	my $href="/adm/pickcode?".
1.359     www      6592: 	   "form=".&escape("scantronupload").
                   6593: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6594: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6595: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6596: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6597: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6598: 	    $r->print("
                   6599:     <label>
                   6600:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6601:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6602: 	     "<a target='_blank' href='$href'>","</a>")."
                   6603:     </label> 
                   6604:     ".&mt("Selected CODE is [_1]","<input readonly='true' type='text' size='8' name='scantron_CODE_selectedvalue' onfocus=\"javascript:change_radio('use_found')\" onchange=\"javascript:change_radio('use_found')\" />"));
1.332     albertel 6605: 	    $r->print("\n<br />");
                   6606: 	}
1.492     albertel 6607: 	$r->print("
                   6608:     <label>
                   6609:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6610:        ".&mt("Use [_1] as the CODE.",
                   6611: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
1.187     albertel 6612: 	$r->print("\n<br /><br />");
1.157     albertel 6613:     } elsif ($error eq 'doublebubble') {
1.492     albertel 6614: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for a some question(s)")."</p>\n");
1.157     albertel 6615: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6616: 		  join(',',@{$arg}).'" />');
1.242     albertel 6617: 	$r->print($message);
1.492     albertel 6618: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6619: 	foreach my $question (@{$arg}) {
1.447     foxr     6620: 	    my $selected  = &get_response_bubbles($scan_record, $question);
1.461     foxr     6621: 	    my @select_array = split(/:/,$selected);
1.422     foxr     6622: 	    &scantron_bubble_selector($r,$scan_config,$question,
1.460     foxr     6623: 				      @select_array);
1.157     albertel 6624: 	}
                   6625:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6626: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6627: 	$r->print($message);
1.492     albertel 6628: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
                   6629: 	$r->print(&mt("Some questions have no scanned bubbles")."\n");
1.157     albertel 6630: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6631: 		  join(',',@{$arg}).'" />');
                   6632: 	foreach my $question (@{$arg}) {
1.448     foxr     6633: 	    my $selected = &get_response_bubbles($scan_record, $question);
1.470     foxr     6634: 	    my @select_array = split(/:/,$selected); # ought to be an array of empties.
                   6635: 	    &scantron_bubble_selector($r,$scan_config,$question, @select_array);
1.157     albertel 6636: 	}
                   6637:     } else {
                   6638: 	$r->print("\n<ul>");
                   6639:     }
                   6640:     $r->print("\n</li></ul>");
                   6641: 
                   6642: }
1.423     albertel 6643: 
                   6644: =pod
                   6645: 
                   6646: =item scantron_bubble_selector
                   6647:   
                   6648:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6649:    possibly showing the existing the selected bubbles if known
1.423     albertel 6650: 
                   6651:  Arguments:
                   6652:     $r           - Apache request object
                   6653:     $scan_config - hash from &get_scantron_config()
                   6654:     $quest       - number of the bubble line to make a corrector for
1.470     foxr     6655:     @lines       - array of answer lines.
1.423     albertel 6656: 
                   6657: =cut
                   6658: 
1.157     albertel 6659: sub scantron_bubble_selector {
1.461     foxr     6660:     my ($r,$scan_config,$quest,@lines)=@_;
1.157     albertel 6661:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6662: 
1.461     foxr     6663: 
1.274     albertel 6664:     my $scmode=$$scan_config{'Qon'};
1.447     foxr     6665: 
1.461     foxr     6666:     my $bubble_length = scalar(@lines);
1.460     foxr     6667: 
1.447     foxr     6668: 
1.274     albertel 6669:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6670: 
1.448     foxr     6671:     my $response = $quest-1;
                   6672:     my $lines = $bubble_lines_per_response{$response};
1.447     foxr     6673: 
1.422     foxr     6674:     my $total_lines = $lines*2;
1.157     albertel 6675:     my @alphabet=('A'..'Z');
1.479     foxr     6676: 
1.422     foxr     6677:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6678: 
                   6679:     for (my $l = 0; $l < $lines; $l++) {
                   6680: 	if ($l != 0) {
                   6681: 	    $r->print('<tr>');
                   6682: 	}
1.462     foxr     6683: 	my @selected = split(//,$lines[$l]);
1.422     foxr     6684: 	for (my $i=0;$i<$max;$i++) {
                   6685: 	    $r->print("\n".'<td align="center">');
                   6686: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6687: 		$r->print('X'); 
                   6688: 		shift(@selected) ;
                   6689: 	    } else { 
                   6690: 		$r->print('&nbsp;'); 
                   6691: 	    }
                   6692: 	    $r->print('</td>');
                   6693: 	    
                   6694: 	}
                   6695: 
                   6696: 	if ($l == 0) {
                   6697: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6698: 
                   6699: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
1.492     albertel 6700: 	      $quest.'" value="none" /> '.&mt('No bubble').' </label></td>');
1.422     foxr     6701: 	
                   6702: 	}
                   6703: 
                   6704: 	$r->print('</tr><tr>');
                   6705: 
                   6706: 	# FIXME: This may have to be a bit more clever for
                   6707: 	#        multiline questions (different values e.g..).
                   6708: 
                   6709: 	for (my $i=0;$i<$max;$i++) {
1.479     foxr     6710: 	    my $value = "$l:$i";	# Relative bubble line #: Bubble in line.
1.422     foxr     6711: 	    $r->print("\n".
                   6712: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
1.479     foxr     6713: 		      $quest.'" value="'.$value.'" />'.$alphabet[$i]."</label></td>");
1.422     foxr     6714: 	}
                   6715: 	$r->print('</tr>');
                   6716: 
                   6717: 	    
1.157     albertel 6718:     }
1.422     foxr     6719:     $r->print('</table>');
1.157     albertel 6720: }
                   6721: 
1.423     albertel 6722: =pod
                   6723: 
                   6724: =item num_matches
                   6725: 
1.424     albertel 6726:    Counts the number of characters that are the same between the two arguments.
                   6727: 
                   6728:  Arguments:
                   6729:    $orig - CODE from the scanline
                   6730:    $code - CODE to match against
                   6731: 
                   6732:  Returns:
                   6733:    $count - integer count of the number of same characters between the
                   6734:             two arguments
                   6735: 
1.423     albertel 6736: =cut
                   6737: 
1.194     albertel 6738: sub num_matches {
                   6739:     my ($orig,$code) = @_;
                   6740:     my @code=split(//,$code);
                   6741:     my @orig=split(//,$orig);
                   6742:     my $same=0;
                   6743:     for (my $i=0;$i<scalar(@code);$i++) {
                   6744: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6745:     }
                   6746:     return $same;
                   6747: }
                   6748: 
1.423     albertel 6749: =pod
                   6750: 
                   6751: =item scantron_get_closely_matching_CODEs
                   6752: 
1.424     albertel 6753:    Cycles through all CODEs and finds the set that has the greatest
                   6754:    number of same characters as the provided CODE
                   6755: 
                   6756:  Arguments:
                   6757:    $allcodes - hash ref returned by &get_codes()
                   6758:    $CODE     - CODE from the current scanline
                   6759: 
                   6760:  Returns:
                   6761:    2 element list
                   6762:     - first elements is number of how closely matching the best fit is 
                   6763:       (5 means best set has 5 matching characters)
                   6764:     - second element is an arrary ref containing the set of valid CODEs
                   6765:       that best fit the passed in CODE
                   6766: 
1.423     albertel 6767: =cut
                   6768: 
1.194     albertel 6769: sub scantron_get_closely_matching_CODEs {
                   6770:     my ($allcodes,$CODE)=@_;
                   6771:     my @CODEs;
                   6772:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6773: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6774:     }
                   6775: 
                   6776:     return ($#CODEs,$CODEs[-1]);
                   6777: }
                   6778: 
1.423     albertel 6779: =pod
                   6780: 
                   6781: =item get_codes
                   6782: 
1.424     albertel 6783:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6784:    set of remembered CODEs.
                   6785: 
                   6786:  Arguments:
                   6787:   $old_name - name of the set of remembered CODEs
                   6788:   $cdom     - domain of the course
                   6789:   $cnum     - internal course name
                   6790: 
                   6791:  Returns:
                   6792:   %allcodes - keys are the valid CODEs, values are all 1
                   6793: 
1.423     albertel 6794: =cut
                   6795: 
1.194     albertel 6796: sub get_codes {
1.280     foxr     6797:     my ($old_name, $cdom, $cnum) = @_;
                   6798:     if (!$old_name) {
                   6799: 	$old_name=$env{'form.scantron_CODElist'};
                   6800:     }
                   6801:     if (!$cdom) {
                   6802: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6803:     }
                   6804:     if (!$cnum) {
                   6805: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6806:     }
1.278     albertel 6807:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6808: 				    $cdom,$cnum);
                   6809:     my %allcodes;
                   6810:     if ($result{"type\0$old_name"} eq 'number') {
                   6811: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6812:     } else {
                   6813: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6814:     }
1.194     albertel 6815:     return %allcodes;
                   6816: }
                   6817: 
1.423     albertel 6818: =pod
                   6819: 
                   6820: =item scantron_validate_CODE
                   6821: 
1.424     albertel 6822:    Validates all scanlines in the selected file to not have any
                   6823:    invalid or underspecified CODEs and that none of the codes are
                   6824:    duplicated if this was requested.
                   6825: 
1.423     albertel 6826: =cut
                   6827: 
1.157     albertel 6828: sub scantron_validate_CODE {
                   6829:     my ($r,$currentphase) = @_;
1.257     albertel 6830:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6831:     if ($scantron_config{'CODElocation'} &&
                   6832: 	$scantron_config{'CODEstart'} &&
                   6833: 	$scantron_config{'CODElength'}) {
1.257     albertel 6834: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6835: 	    &FIXME_blow_up()
                   6836: 	}
                   6837:     } else {
                   6838: 	return (0,$currentphase+1);
                   6839:     }
                   6840:     
                   6841:     my %usedCODEs;
                   6842: 
1.194     albertel 6843:     my %allcodes=&get_codes();
1.186     albertel 6844: 
1.447     foxr     6845:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   6846: 
1.186     albertel 6847:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6848:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6849: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6850: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6851: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6852: 						 $scan_data);
                   6853: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6854: 	my $error=0;
1.224     albertel 6855: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6856: 	    &scantron_get_correction($r,$i,$scan_record,
                   6857: 				     \%scantron_config,
                   6858: 				     $line,'incorrectCODE',\%allcodes);
                   6859: 	    return(1,$currentphase);
                   6860: 	}
1.221     albertel 6861: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6862: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6863: 	    &scantron_get_correction($r,$i,$scan_record,
                   6864: 				     \%scantron_config,
1.194     albertel 6865: 				     $line,'incorrectCODE',\%allcodes);
                   6866: 	    return(1,$currentphase);
1.186     albertel 6867: 	}
1.214     albertel 6868: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6869: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6870: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6871: 	    &scantron_get_correction($r,$i,$scan_record,
                   6872: 				     \%scantron_config,
1.194     albertel 6873: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6874: 	    return(1,$currentphase);
1.186     albertel 6875: 	}
1.194     albertel 6876: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6877:     }
1.157     albertel 6878:     return (0,$currentphase+1);
                   6879: }
                   6880: 
1.423     albertel 6881: =pod
                   6882: 
                   6883: =item scantron_validate_doublebubble
                   6884: 
1.424     albertel 6885:    Validates all scanlines in the selected file to not have any
                   6886:    bubble lines with multiple bubbles marked.
                   6887: 
1.423     albertel 6888: =cut
                   6889: 
1.157     albertel 6890: sub scantron_validate_doublebubble {
                   6891:     my ($r,$currentphase) = @_;
                   6892:     #get student info
                   6893:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6894:     my %idmap=&username_to_idmap($classlist);
                   6895: 
                   6896:     #get scantron line setup
1.257     albertel 6897:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6898:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6899: 
                   6900:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   6901: 
1.157     albertel 6902:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6903: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6904: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6905: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6906: 						 $scan_data);
                   6907: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6908: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6909: 				 'doublebubble',
                   6910: 				 $$scan_record{'scantron.doubleerror'});
                   6911:     	return (1,$currentphase);
                   6912:     }
                   6913:     return (0,$currentphase+1);
                   6914: }
                   6915: 
1.423     albertel 6916: =pod
                   6917: 
                   6918: =item scantron_get_maxbubble
                   6919: 
1.424     albertel 6920:    Returns the maximum number of bubble lines that are expected to
                   6921:    occur. Does this by walking the selected sequence rendering the
                   6922:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6923:    for what the current value of the problem counter is.
                   6924: 
1.447     foxr     6925:    Caches the results to $env{'form.scantron_maxbubble'},
                   6926:    $env{'form.scantron.bubble_lines.n'} and 
                   6927:    $env{'form.scantron.first_bubble_line.n'}
                   6928:    which are the total number of bubble, lines, the number of bubble
                   6929:    lines for reponse n and number of the first bubble line for response n.
1.424     albertel 6930: 
1.423     albertel 6931: =cut
                   6932: 
1.330     albertel 6933: sub scantron_get_maxbubble {    
1.257     albertel 6934:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6935: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     6936: 	&restore_bubble_lines();
1.257     albertel 6937: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6938:     }
1.330     albertel 6939: 
1.447     foxr     6940:     my (undef, undef, $sequence) =
1.257     albertel 6941: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6942: 
1.447     foxr     6943:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 6944:     my $map=$navmap->getResourceByUrl($sequence);
                   6945:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6946: 
                   6947:     &Apache::lonxml::clear_problem_counter();
                   6948: 
1.435     foxr     6949:     my $uname       = $env{'form.student'};
                   6950:     my $udom        = $env{'form.userdom'};
                   6951:     my $cid         = $env{'request.course.id'};
                   6952:     my $total_lines = 0;
                   6953:     %bubble_lines_per_response = ();
1.447     foxr     6954:     %first_bubble_line         = ();
1.435     foxr     6955: 
1.447     foxr     6956:   
                   6957:     my $response_number = 0;
                   6958:     my $bubble_line     = 0;
1.191     albertel 6959:     foreach my $resource (@resources) {
1.435     foxr     6960: 	my $symb = $resource->symb();
1.330     albertel 6961: 	my $result=&Apache::lonnet::ssi($resource->src(),
1.435     foxr     6962: 					('symb' => $resource->symb()),
                   6963: 					('grade_target' => 'analyze'),
                   6964: 					('grade_courseid' => $cid),
                   6965: 					('grade_domain' => $udom),
                   6966: 					('grade_username' => $uname));
1.436     albertel 6967: 	my (undef, $an) =
1.435     foxr     6968: 	    split(/_HASH_REF__/,$result, 2);
                   6969: 
                   6970: 	my %analysis = &Apache::lonnet::str2hash($an);
                   6971: 
                   6972: 
                   6973: 
                   6974: 	foreach my $part_id (@{$analysis{'parts'}}) {
1.447     foxr     6975: 
1.490     foxr     6976: 	    my $lines = $analysis{"$part_id.bubble_lines"};;
                   6977: 
1.460     foxr     6978: 
1.447     foxr     6979: 
                   6980: 	    # TODO - make this a persistent hash not an array.
                   6981: 
                   6982: 
                   6983: 	    $first_bubble_line{$response_number}           = $bubble_line;
                   6984: 	    $bubble_lines_per_response{$response_number}   = $lines;
                   6985: 	    $response_number++;
                   6986: 
                   6987: 	    $bubble_line +=  $lines;
                   6988: 	    $total_lines +=  $lines;
1.435     foxr     6989: 	}
                   6990: 
1.191     albertel 6991:     }
                   6992:     &Apache::lonnet::delenv('scantron\.');
1.447     foxr     6993: 
                   6994:     &save_bubble_lines();
1.330     albertel 6995:     $env{'form.scantron_maxbubble'} =
1.435     foxr     6996: 	$total_lines;
1.257     albertel 6997:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6998: }
                   6999: 
1.423     albertel 7000: =pod
                   7001: 
                   7002: =item scantron_validate_missingbubbles
                   7003: 
1.424     albertel 7004:    Validates all scanlines in the selected file to not have any
1.447     foxr     7005:     answers that don't have bubbles that have not been verified
                   7006:     to be bubble free.
1.424     albertel 7007: 
1.423     albertel 7008: =cut
                   7009: 
1.157     albertel 7010: sub scantron_validate_missingbubbles {
                   7011:     my ($r,$currentphase) = @_;
                   7012:     #get student info
                   7013:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7014:     my %idmap=&username_to_idmap($classlist);
                   7015: 
                   7016:     #get scantron line setup
1.257     albertel 7017:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7018:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 7019:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 7020:     if (!$max_bubble) { $max_bubble=2**31; }
                   7021:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7022: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7023: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7024: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7025: 						 $scan_data);
                   7026: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7027: 	my @to_correct;
1.470     foxr     7028: 	
                   7029: 	# Probably here's where the error is...
                   7030: 
1.157     albertel 7031: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   7032: 	    if ($missing > $max_bubble) { next; }
                   7033: 	    push(@to_correct,$missing);
                   7034: 	}
                   7035: 	if (@to_correct) {
                   7036: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7037: 				     $line,'missingbubble',\@to_correct);
                   7038: 	    return (1,$currentphase);
                   7039: 	}
                   7040: 
                   7041:     }
                   7042:     return (0,$currentphase+1);
                   7043: }
                   7044: 
1.423     albertel 7045: =pod
                   7046: 
                   7047: =item scantron_process_students
                   7048: 
                   7049:    Routine that does the actual grading of the bubble sheet information.
                   7050: 
                   7051:    The parsed scanline hash is added to %env 
                   7052: 
                   7053:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   7054:    foreach resource , with the form data of
                   7055: 
                   7056: 	'submitted'     =>'scantron' 
                   7057: 	'grade_target'  =>'grade',
                   7058: 	'grade_username'=> username of student
                   7059: 	'grade_domain'  => domain of student
                   7060: 	'grade_courseid'=> of course
                   7061: 	'grade_symb'    => symb of resource to grade
                   7062: 
                   7063:     This triggers a grading pass. The problem grading code takes care
                   7064:     of converting the bubbled letter information (now in %env) into a
                   7065:     valid submission.
                   7066: 
                   7067: =cut
                   7068: 
1.82      albertel 7069: sub scantron_process_students {
1.75      albertel 7070:     my ($r) = @_;
1.257     albertel 7071:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7072:     my ($symb)=&get_symb($r);
1.81      albertel 7073:     if (!$symb) {return '';}
1.324     albertel 7074:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7075: 
1.257     albertel 7076:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7077:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7078:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7079:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7080:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 7081:     my $map=$navmap->getResourceByUrl($sequence);
                   7082:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 7083: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 7084:     my $result= <<SCANTRONFORM;
1.81      albertel 7085: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7086:   <input type="hidden" name="command" value="scantron_configphase" />
                   7087:   $default_form_data
                   7088: SCANTRONFORM
1.82      albertel 7089:     $r->print($result);
                   7090: 
                   7091:     my @delayqueue;
1.140     albertel 7092:     my %completedstudents;
                   7093:     
1.200     albertel 7094:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 7095:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 7096:  				    'Scantron Progress',$count,
1.195     albertel 7097: 				    'inline',undef,'scantronupload');
1.140     albertel 7098:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7099: 					  'Processing first student');
                   7100:     my $start=&Time::HiRes::time();
1.158     albertel 7101:     my $i=-1;
1.200     albertel 7102:     my ($uname,$udom,$started);
1.447     foxr     7103: 
                   7104:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
                   7105: 
1.157     albertel 7106:     while ($i<$scanlines->{'count'}) {
                   7107:  	($uname,$udom)=('','');
                   7108:  	$i++;
1.200     albertel 7109:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7110:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7111: 	if ($started) {
                   7112: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7113: 						     'last student');
                   7114: 	}
                   7115: 	$started=1;
1.157     albertel 7116:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7117:  						 $scan_data);
                   7118:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7119:  					      \%idmap,$i)) {
                   7120:   	    &scantron_add_delay(\@delayqueue,$line,
                   7121:  				'Unable to find a student that matches',1);
                   7122:  	    next;
                   7123:   	}
                   7124:  	if (exists $completedstudents{$uname}) {
                   7125:  	    &scantron_add_delay(\@delayqueue,$line,
                   7126:  				'Student '.$uname.' has multiple sheets',2);
                   7127:  	    next;
                   7128:  	}
                   7129:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7130: 
                   7131: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 7132:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 7133: 
                   7134: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7135: 	    &scantron_putfile($scanlines,$scan_data);
                   7136: 	}
1.161     albertel 7137: 	
                   7138: 	my $i=0;
1.83      albertel 7139: 	foreach my $resource (@resources) {
1.85      albertel 7140: 	    $i++;
1.193     albertel 7141: 	    my %form=('submitted'     =>'scantron',
                   7142: 		      'grade_target'  =>'grade',
                   7143: 		      'grade_username'=>$uname,
                   7144: 		      'grade_domain'  =>$udom,
1.257     albertel 7145: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 7146: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 7147: 	    if (exists($scan_record->{'scantron.CODE'})
                   7148: 		&& 
                   7149: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 7150: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 7151: 	    } else {
                   7152: 		$form{'CODE'}='';
1.193     albertel 7153: 	    }
                   7154: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 7155: 	    if ($result ne '') {
                   7156: 	    }
1.213     albertel 7157: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 7158: 	}
1.140     albertel 7159: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 7160: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7161:     } continue {
1.330     albertel 7162: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 7163: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 7164:     }
1.140     albertel 7165:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 7166: #    my $lasttime = &Time::HiRes::time()-$start;
                   7167: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7168: 
1.200     albertel 7169:     $r->print("</form>");
1.324     albertel 7170:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7171:     return '';
1.75      albertel 7172: }
1.157     albertel 7173: 
1.423     albertel 7174: =pod
                   7175: 
                   7176: =item scantron_upload_scantron_data
                   7177: 
                   7178:     Creates the screen for adding a new bubble sheet data file to a course.
                   7179: 
                   7180: =cut
                   7181: 
1.157     albertel 7182: sub scantron_upload_scantron_data {
                   7183:     my ($r)=@_;
1.257     albertel 7184:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 7185:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7186: 							  'domainid',
                   7187: 							  'coursename');
1.257     albertel 7188:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 7189: 						   'domainid');
1.324     albertel 7190:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.492     albertel 7191:     $r->print('
1.157     albertel 7192: <script type="text/javascript" language="javascript">
                   7193:     function checkUpload(formname) {
                   7194: 	if (formname.upfile.value == "") {
                   7195: 	    alert("Please use the browse button to select a file from your local directory.");
                   7196: 	    return false;
                   7197: 	}
                   7198: 	formname.submit();
                   7199:     }
                   7200: </script>
                   7201: 
1.492     albertel 7202: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   7203: '.$default_form_data.'
1.181     albertel 7204: <table>
1.492     albertel 7205: <tr><td>'.$select_link.'                             </td></tr>
                   7206: <tr><td>'.&mt('Course ID:').'     </td>
                   7207:     <td><input name="courseid"   type="text" />      </td></tr>
                   7208: <tr><td>'.&mt('Course Name:').'   </td>
                   7209:     <td><input name="coursename" type="text" />      </td></tr>
                   7210: <tr><td>'.&mt('Domain:').'        </td>
                   7211:     <td>'.$domsel.'                                  </td></tr>
                   7212: <tr><td>'.&mt('File to upload:').'</td>
                   7213:     <td><input type="file" name="upfile" size="50" /></td></tr>
1.181     albertel 7214: </table>
1.492     albertel 7215: <input name="command" value="scantronupload_save" type="hidden" />
                   7216: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.157     albertel 7217: </form>
1.492     albertel 7218: ');
1.157     albertel 7219:     return '';
                   7220: }
                   7221: 
1.423     albertel 7222: =pod
                   7223: 
                   7224: =item scantron_upload_scantron_data_save
                   7225: 
                   7226:    Adds a provided bubble information data file to the course if user
                   7227:    has the correct privileges to do so.  
                   7228: 
                   7229: =cut
                   7230: 
1.157     albertel 7231: sub scantron_upload_scantron_data_save {
                   7232:     my($r)=@_;
1.324     albertel 7233:     my ($symb)=&get_symb($r,1);
1.182     albertel 7234:     my $doanotherupload=
                   7235: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7236: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7237: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7238: 	'</form>'."\n";
1.257     albertel 7239:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7240: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7241: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.492     albertel 7242: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
1.182     albertel 7243: 	if ($symb) {
1.324     albertel 7244: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7245: 	} else {
                   7246: 	    $r->print($doanotherupload);
                   7247: 	}
1.162     albertel 7248: 	return '';
                   7249:     }
1.257     albertel 7250:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.492     albertel 7251:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
1.257     albertel 7252:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7253:     #FIXME
                   7254:     #copied from lonnet::userfileupload()
                   7255:     #make that function able to target a specified course
                   7256:     # Replace Windows backslashes by forward slashes
                   7257:     $fname=~s/\\/\//g;
                   7258:     # Get rid of everything but the actual filename
                   7259:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7260:     # Replace spaces by underscores
                   7261:     $fname=~s/\s+/\_/g;
                   7262:     # Replace all other weird characters by nothing
                   7263:     $fname=~s/[^\w\.\-]//g;
                   7264:     # See if there is anything left
                   7265:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7266:     my $uploadedfile=$fname;
1.157     albertel 7267:     $fname='scantron_orig_'.$fname;
1.257     albertel 7268:     if (length($env{'form.upfile'}) < 2) {
1.492     albertel 7269: 	$r->print(&mt("<span class=\"LC_error\">Error:</span> The file you attempted to upload, [_1]  contained no information. Please check that you entered the correct filename.",'<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
1.183     albertel 7270:     } else {
1.275     albertel 7271: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7272: 	if ($result =~ m|^/uploaded/|) {
1.492     albertel 7273: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
                   7274: 			  (length($env{'form.upfile'})-1),
                   7275: 			  '<span class="LC_filename">'.$result."</span>"));
1.210     albertel 7276: 	} else {
1.492     albertel 7277: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
                   7278: 			  $result,
                   7279: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
                   7280: 
1.183     albertel 7281: 	}
                   7282:     }
1.174     albertel 7283:     if ($symb) {
1.209     ng       7284: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7285:     } else {
1.182     albertel 7286: 	$r->print($doanotherupload);
1.174     albertel 7287:     }
1.157     albertel 7288:     return '';
                   7289: }
                   7290: 
1.423     albertel 7291: =pod
                   7292: 
                   7293: =item valid_file
                   7294: 
1.424     albertel 7295:    Validates that the requested bubble data file exists in the course.
1.423     albertel 7296: 
                   7297: =cut
                   7298: 
1.202     albertel 7299: sub valid_file {
                   7300:     my ($requested_file)=@_;
                   7301:     foreach my $filename (sort(&scantron_filenames())) {
                   7302: 	if ($requested_file eq $filename) { return 1; }
                   7303:     }
                   7304:     return 0;
                   7305: }
                   7306: 
1.423     albertel 7307: =pod
                   7308: 
                   7309: =item scantron_download_scantron_data
                   7310: 
                   7311:    Shows a list of the three internal files (original, corrected,
                   7312:    skipped) for a specific bubble sheet data file that exists in the
                   7313:    course.
                   7314: 
                   7315: =cut
                   7316: 
1.202     albertel 7317: sub scantron_download_scantron_data {
                   7318:     my ($r)=@_;
1.324     albertel 7319:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7320:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7321:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7322:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7323:     if (! &valid_file($file)) {
1.492     albertel 7324: 	$r->print('
1.202     albertel 7325: 	<p>
1.492     albertel 7326: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 7327:         </p>
1.492     albertel 7328: ');
1.324     albertel 7329: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7330: 	return;
                   7331:     }
                   7332:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7333:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7334:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7335:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7336:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7337:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 7338:     $r->print('
1.202     albertel 7339:     <p>
1.492     albertel 7340: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   7341: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 7342:     </p>
                   7343:     <p>
1.492     albertel 7344: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   7345: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 7346:     </p>
                   7347:     <p>
1.492     albertel 7348: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   7349: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 7350:     </p>
1.492     albertel 7351: ');
1.324     albertel 7352:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7353:     return '';
                   7354: }
1.157     albertel 7355: 
1.423     albertel 7356: =pod
                   7357: 
                   7358: =back
                   7359: 
                   7360: =cut
                   7361: 
1.75      albertel 7362: #-------- end of section for handling grading scantron forms -------
                   7363: #
                   7364: #-------------------------------------------------------------------
                   7365: 
1.72      ng       7366: #-------------------------- Menu interface -------------------------
                   7367: #
                   7368: #--- Show a Grading Menu button - Calls the next routine ---
                   7369: sub show_grading_menu_form {
1.324     albertel 7370:     my ($symb)=@_;
1.125     ng       7371:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 7372: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 7373: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       7374: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 7375: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       7376: 	'</form>'."\n";
                   7377:     return $result;
                   7378: }
                   7379: 
1.77      ng       7380: # -- Retrieve choices for grading form
                   7381: sub savedState {
                   7382:     my %savedState = ();
1.257     albertel 7383:     if ($env{'form.saveState'}) {
                   7384: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       7385: 	    my ($key,$value) = split(/=/,$_,2);
                   7386: 	    $savedState{$key} = $value;
                   7387: 	}
                   7388:     }
                   7389:     return \%savedState;
                   7390: }
1.76      ng       7391: 
1.443     banghart 7392: sub grading_menu {
                   7393:     my ($request) = @_;
                   7394:     my ($symb)=&get_symb($request);
                   7395:     if (!$symb) {return '';}
                   7396:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   7397:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   7398: 
1.444     banghart 7399:     $request->print($table);
1.443     banghart 7400:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   7401:                   'handgrade'=>$hdgrade,
                   7402:                   'probTitle'=>$probTitle,
                   7403:                   'command'=>'submit_options',
                   7404:                   'saveState'=>"",
                   7405:                   'gradingMenu'=>1,
                   7406:                   'showgrading'=>"yes");
                   7407:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7408:     my @menu = ({ url => $url,
                   7409:                      name => &mt('Manual Grading/View Submissions'),
                   7410:                      short_description => 
                   7411:     &mt('Start the process of hand grading submissions.'),
                   7412:                  });
                   7413:     $fields{'command'} = 'csvform';
                   7414:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7415:     push (@menu, { url => $url,
                   7416:                    name => &mt('Upload Scores'),
                   7417:                    short_description => 
                   7418:             &mt('Specify a file containing the class scores for current resource.')});
                   7419:     $fields{'command'} = 'processclicker';
                   7420:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7421:     push (@menu, { url => $url,
                   7422:                    name => &mt('Process Clicker'),
                   7423:                    short_description => 
                   7424:             &mt('Specify a file containing the clicker information for this resource.')});
                   7425:     $fields{'command'} = 'scantron_selectphase';
                   7426:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7427:     push (@menu, { url => $url,
1.454     banghart 7428:                    name => &mt('Grade/Manage Scantron Forms'),
                   7429:                    short_description => 
                   7430:             &mt('')});
1.443     banghart 7431:     $fields{'command'} = 'verify';
                   7432:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.445     banghart 7433:     push (@menu, { url => "",
1.443     banghart 7434:                    name => &mt('Verify Receipt'),
                   7435:                    short_description => 
                   7436:             &mt('')});
                   7437:     #
                   7438:     # Create the menu
                   7439:     my $Str;
1.444     banghart 7440:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 7441:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   7442:     $Str .= '<input type="hidden" name="command" value="" />'.
                   7443:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7444: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 7445: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 7446: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7447: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7448: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7449: 
1.443     banghart 7450:     foreach my $menudata (@menu) {
1.445     banghart 7451:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   7452:             $Str .='    <h3><a '.
                   7453:                 $menudata->{'jscript'}.
                   7454:                 ' href="'.
                   7455:                 $menudata->{'url'}.'" >'.
                   7456:                 $menudata->{'name'}."</a></h3>\n";
                   7457:         } else {
1.485     albertel 7458:             $Str .='    <h3><input type="button" value="'.&mt('Verify Receipt').'" '.
1.445     banghart 7459:                 $menudata->{'jscript'}.
1.458     banghart 7460:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
                   7461:                 ' /></h3>';
1.446     banghart 7462:             $Str .= ('&nbsp;'x8).
1.485     albertel 7463: 		&mt(' receipt: [_1]',
                   7464: 		    &Apache::lonnet::recprefix($env{'request.course.id'}).
                   7465:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />');
1.444     banghart 7466:         }
1.443     banghart 7467:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   7468:             "\n";
                   7469:     }
1.444     banghart 7470:     $Str .="</form>\n";
1.443     banghart 7471:     $request->print(<<GRADINGMENUJS);
                   7472: <script type="text/javascript" language="javascript">
                   7473:     function checkChoice(formname,val,cmdx) {
                   7474: 	if (val <= 2) {
                   7475: 	    var cmd = radioSelection(formname.radioChoice);
                   7476: 	    var cmdsave = cmd;
                   7477: 	} else {
                   7478: 	    cmd = cmdx;
                   7479: 	    cmdsave = 'submission';
                   7480: 	}
                   7481: 	formname.command.value = cmd;
                   7482: 	if (val < 5) formname.submit();
                   7483: 	if (val == 5) {
1.458     banghart 7484: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   7485: 	        return false;
                   7486: 	    } else {
                   7487: 	        formname.submit();
                   7488: 	    }
1.445     banghart 7489: 	}
                   7490:     }
1.443     banghart 7491: 
                   7492:     function checkReceiptNo(formname,nospace) {
                   7493: 	var receiptNo = formname.receipt.value;
                   7494: 	var checkOpt = false;
                   7495: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7496: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7497: 	if (checkOpt) {
                   7498: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7499: 	    formname.receipt.value = "";
                   7500: 	    formname.receipt.focus();
                   7501: 	    return false;
                   7502: 	}
                   7503: 	return true;
                   7504:     }
                   7505: </script>
                   7506: GRADINGMENUJS
                   7507:     &commonJSfunctions($request);
                   7508:     return $Str;    
                   7509: }
                   7510: 
                   7511: 
                   7512: #--- Displays the submissions first page -------
                   7513: sub submit_options {
1.72      ng       7514:     my ($request) = @_;
1.324     albertel 7515:     my ($symb)=&get_symb($request);
1.72      ng       7516:     if (!$symb) {return '';}
1.76      ng       7517:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       7518: 
                   7519:     $request->print(<<GRADINGMENUJS);
                   7520: <script type="text/javascript" language="javascript">
1.116     ng       7521:     function checkChoice(formname,val,cmdx) {
                   7522: 	if (val <= 2) {
                   7523: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       7524: 	    var cmdsave = cmd;
1.116     ng       7525: 	} else {
                   7526: 	    cmd = cmdx;
1.118     ng       7527: 	    cmdsave = 'submission';
1.116     ng       7528: 	}
                   7529: 	formname.command.value = cmd;
1.118     ng       7530: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 7531: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       7532: 	if (val < 5) formname.submit();
                   7533: 	if (val == 5) {
1.72      ng       7534: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7535: 	    formname.submit();
                   7536: 	}
1.238     albertel 7537: 	if (val < 7) formname.submit();
1.72      ng       7538:     }
                   7539: 
                   7540:     function checkReceiptNo(formname,nospace) {
                   7541: 	var receiptNo = formname.receipt.value;
                   7542: 	var checkOpt = false;
                   7543: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7544: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7545: 	if (checkOpt) {
                   7546: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7547: 	    formname.receipt.value = "";
                   7548: 	    formname.receipt.focus();
                   7549: 	    return false;
                   7550: 	}
                   7551: 	return true;
                   7552:     }
                   7553: </script>
                   7554: GRADINGMENUJS
1.118     ng       7555:     &commonJSfunctions($request);
1.324     albertel 7556:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 7557:     my $result;
1.76      ng       7558:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       7559:     my $savedState = &savedState();
1.118     ng       7560:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       7561:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       7562:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       7563:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       7564: 
                   7565:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 7566: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       7567: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7568: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       7569: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       7570: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       7571: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       7572: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7573: 
1.472     albertel 7574:     $result.='
                   7575:     <div class="LC_grade_select_mode">
1.473     albertel 7576:       <div class="LC_grade_select_mode_current">
                   7577:         <h2>
                   7578:           '.&mt('Grade Current Resource').'
                   7579:         </h2>
                   7580:         <div class="LC_grade_select_mode_body">
                   7581:           <div class="LC_grades_resource_info">
                   7582:            '.$table.'
                   7583:           </div>
                   7584:           <div class="LC_grade_select_mode_selector">
                   7585:              <div class="LC_grade_select_mode_selector_header">
                   7586:                 '.&mt('Sections').'
                   7587:              </div>
                   7588:              <div class="LC_grade_select_mode_selector_body">
                   7589: 	       <select name="section" multiple="multiple" size="5">'."\n";
1.116     ng       7590:     if (ref($sections)) {
1.472     albertel 7591: 	foreach my $section (sort (@$sections)) {
                   7592: 	    $result.='<option value="'.$section.'" '.
                   7593: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
1.155     albertel 7594: 	}
1.116     ng       7595:     }
1.401     albertel 7596:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 7597:     $result.='
1.473     albertel 7598:              </div>
                   7599:           </div>
                   7600:           <div class="LC_grade_select_mode_selector">
                   7601:              <div class="LC_grade_select_mode_selector_header">
                   7602:                 '.&mt('Groups').'
                   7603:              </div>
                   7604:              <div class="LC_grade_select_mode_selector_body">
                   7605:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   7606:              </div>
1.472     albertel 7607:           </div>
1.473     albertel 7608:           <div class="LC_grade_select_mode_selector">
                   7609:              <div class="LC_grade_select_mode_selector_header">
                   7610:                 '.&mt('Access Status').'
                   7611:              </div>
                   7612:              <div class="LC_grade_select_mode_selector_body">
                   7613:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   7614:              </div>
1.472     albertel 7615:           </div>
1.473     albertel 7616:           <div class="LC_grade_select_mode_selector">
                   7617:              <div class="LC_grade_select_mode_selector_header">
                   7618:                 '.&mt('Submission Status').'
                   7619:              </div>
                   7620:              <div class="LC_grade_select_mode_selector_body">
                   7621:                <select name="submitonly" size="5">
                   7622: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   7623: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   7624: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   7625: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   7626:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
                   7627:                </select>
                   7628:              </div>
1.472     albertel 7629:           </div>
1.473     albertel 7630:           <div class="LC_grade_select_mode_type_body">
                   7631:             <div class="LC_grade_select_mode_type">
                   7632:               <label>
                   7633:                 <input type="radio" name="radioChoice" value="submission" '.
                   7634:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   7635:              &mt('Select individual students to grade and view submissions.').'
                   7636: 	      </label> 
                   7637:             </div>
                   7638:             <div class="LC_grade_select_mode_type">
                   7639: 	      <label>
                   7640:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   7641:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   7642:                     &mt('Grade all selected students in a grading table.').'
                   7643:               </label>
                   7644:             </div>
                   7645:             <div class="LC_grade_select_mode_type">
                   7646: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   7647:             </div>
1.472     albertel 7648:           </div>
1.473     albertel 7649:         </div>
                   7650:       </div>
                   7651:       <div class="LC_grade_select_mode_page">
                   7652:         <h2>
                   7653:          '.&mt('Grade Complete Folder for One Student').'
                   7654:         </h2>
                   7655:         <div class="LC_grades_select_mode_body">
                   7656:           <div class="LC_grade_select_mode_type_body">
                   7657:             <div class="LC_grade_select_mode_type">
                   7658:               <label>
                   7659:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   7660: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   7661:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   7662:               </label>
                   7663:             </div>
                   7664:             <div class="LC_grade_select_mode_type">
                   7665: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   7666:             </div>
1.472     albertel 7667:           </div>
                   7668:         </div>
                   7669:       </div>
                   7670:     </div>
                   7671:   </form>';
1.44      ng       7672:     return $result;
1.2       albertel 7673: }
                   7674: 
1.285     albertel 7675: sub reset_perm {
                   7676:     undef(%perm);
                   7677: }
                   7678: 
                   7679: sub init_perm {
                   7680:     &reset_perm();
1.300     albertel 7681:     foreach my $test_perm ('vgr','mgr','opa') {
                   7682: 
                   7683: 	my $scope = $env{'request.course.id'};
                   7684: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7685: 
                   7686: 	    $scope .= '/'.$env{'request.course.sec'};
                   7687: 	    if ( $perm{$test_perm}=
                   7688: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7689: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7690: 	    } else {
                   7691: 		delete($perm{$test_perm});
                   7692: 	    }
1.285     albertel 7693: 	}
                   7694:     }
                   7695: }
                   7696: 
1.400     www      7697: sub gather_clicker_ids {
1.408     albertel 7698:     my %clicker_ids;
1.400     www      7699: 
                   7700:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7701: 
                   7702:     # Set up a couple variables.
1.407     albertel 7703:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7704:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      7705:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      7706: 
1.407     albertel 7707:     foreach my $student (keys(%$classlist)) {
1.438     www      7708:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 7709:         my $username = $classlist->{$student}->[$username_idx];
                   7710:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7711:         my $clickers =
1.408     albertel 7712: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7713:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7714:             $id=~s/^[\#0]+//;
1.421     www      7715:             $id=~s/[\-\:]//g;
1.407     albertel 7716:             if (exists($clicker_ids{$id})) {
1.408     albertel 7717: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7718:             } else {
1.408     albertel 7719: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7720:             }
                   7721:         }
                   7722:     }
1.407     albertel 7723:     return %clicker_ids;
1.400     www      7724: }
                   7725: 
1.402     www      7726: sub gather_adv_clicker_ids {
1.408     albertel 7727:     my %clicker_ids;
1.402     www      7728:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7729:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7730:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7731:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7732:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7733:             my ($puname,$pudom)=split(/\:/,$person);
                   7734:             my $clickers =
1.408     albertel 7735: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7736:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7737: 		$id=~s/^[\#0]+//;
1.421     www      7738:                 $id=~s/[\-\:]//g;
1.408     albertel 7739: 		if (exists($clicker_ids{$id})) {
                   7740: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7741: 		} else {
                   7742: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7743: 		}
1.405     www      7744:             }
1.402     www      7745:         }
                   7746:     }
1.407     albertel 7747:     return %clicker_ids;
1.402     www      7748: }
                   7749: 
1.413     www      7750: sub clicker_grading_parameters {
                   7751:     return ('gradingmechanism' => 'scalar',
                   7752:             'upfiletype' => 'scalar',
                   7753:             'specificid' => 'scalar',
                   7754:             'pcorrect' => 'scalar',
                   7755:             'pincorrect' => 'scalar');
                   7756: }
                   7757: 
1.400     www      7758: sub process_clicker {
                   7759:     my ($r)=@_;
                   7760:     my ($symb)=&get_symb($r);
                   7761:     if (!$symb) {return '';}
                   7762:     my $result=&checkforfile_js();
                   7763:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7764:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7765:     $result.=$table;
                   7766:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7767:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7768:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7769:         '.</b></td></tr>'."\n";
                   7770:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7771: # Attempt to restore parameters from last session, set defaults if not present
                   7772:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7773:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7774:                                                  \%Saveable_Parameters);
                   7775:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7776:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7777:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7778:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7779: 
                   7780:     my %checked;
                   7781:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7782:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7783:           $checked{$gradingmechanism}="checked='checked'";
                   7784:        }
                   7785:     }
                   7786: 
1.400     www      7787:     my $upload=&mt("Upload File");
                   7788:     my $type=&mt("Type");
1.402     www      7789:     my $attendance=&mt("Award points just for participation");
                   7790:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7791:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7792:     my $pcorrect=&mt("Percentage points for correct solution");
                   7793:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7794:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7795: 						   ('iclicker' => 'i>clicker',
                   7796:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7797:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7798:     $result.=<<ENDUPFORM;
1.402     www      7799: <script type="text/javascript">
                   7800: function sanitycheck() {
                   7801: // Accept only integer percentages
                   7802:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7803:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7804: // Find out grading choice
                   7805:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7806:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7807:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7808:       }
                   7809:    }
                   7810: // By default, new choice equals user selection
                   7811:    newgradingchoice=gradingchoice;
                   7812: // Not good to give more points for false answers than correct ones
                   7813:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7814:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7815:    }
                   7816: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7817:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7818:       document.forms.gradesupload.pcorrect.value=100;
                   7819:       document.forms.gradesupload.pincorrect.value=100;
                   7820:    }
                   7821: // If the values are different, cannot be attendance only
                   7822:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7823:        (gradingchoice=='attendance')) {
                   7824:        newgradingchoice='personnel';
                   7825:    }
                   7826: // Change grading choice to new one
                   7827:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7828:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7829:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7830:       } else {
                   7831:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7832:       }
                   7833:    }
                   7834: // Remember the old state
                   7835:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7836: }
                   7837: </script>
1.400     www      7838: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7839: <input type="hidden" name="symb" value="$symb" />
                   7840: <input type="hidden" name="command" value="processclickerfile" />
                   7841: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7842: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7843: <input type="file" name="upfile" size="50" />
                   7844: <br /><label>$type: $selectform</label>
1.451     albertel 7845: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   7846: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   7847: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      7848: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7849: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7850: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7851: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7852: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7853: </form>
                   7854: ENDUPFORM
                   7855:     $result.='</td></tr></table>'."\n".
                   7856:              '</td></tr></table><br /><br />'."\n";
                   7857:     $result.=&show_grading_menu_form($symb);
                   7858:     return $result;
                   7859: }
                   7860: 
                   7861: sub process_clicker_file {
                   7862:     my ($r)=@_;
                   7863:     my ($symb)=&get_symb($r);
                   7864:     if (!$symb) {return '';}
1.413     www      7865: 
                   7866:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7867:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7868:                                               \%Saveable_Parameters);
                   7869: 
1.400     www      7870:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7871:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7872: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7873: 	return $result.&show_grading_menu_form($symb);
1.404     www      7874:     }
1.407     albertel 7875:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7876:     my %correct_ids;
1.404     www      7877:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7878: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7879:     }
                   7880:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7881: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7882: 	   $correct_id=~tr/a-z/A-Z/;
                   7883: 	   $correct_id=~s/\s//gs;
                   7884: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7885:            $correct_id=~s/[\-\:]//g;
1.414     www      7886:            if ($correct_id) {
                   7887: 	      $correct_ids{$correct_id}='specified';
                   7888:            }
                   7889:         }
1.400     www      7890:     }
1.404     www      7891:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7892: 	$result.=&mt('Score based on attendance only');
1.404     www      7893:     } else {
1.408     albertel 7894: 	my $number=0;
1.411     www      7895: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7896: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7897: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7898: 	    if ($correct_ids{$id} eq 'specified') {
                   7899: 		$result.=&mt('specified');
                   7900: 	    } else {
                   7901: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7902: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7903: 	    }
                   7904: 	    $number++;
                   7905: 	}
1.411     www      7906:         $result.="</p>\n";
1.408     albertel 7907: 	if ($number==0) {
                   7908: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7909: 	    return $result.&show_grading_menu_form($symb);
                   7910: 	}
1.404     www      7911:     }
1.405     www      7912:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7913:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7914: 		     '<span class="LC_error">',
                   7915: 		     '</span>',
                   7916: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7917:         return $result.&show_grading_menu_form($symb);
                   7918:     }
1.410     www      7919: 
                   7920: # Were able to get all the info needed, now analyze the file
                   7921: 
1.411     www      7922:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7923:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7924:     my $heading=&mt('Scanning clicker file');
                   7925:     $result.=(<<ENDHEADER);
                   7926: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7927: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7928: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7929: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7930: <input type="hidden" name="symb" value="$symb" />
                   7931: <input type="hidden" name="command" value="assignclickergrades" />
                   7932: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7933: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7934: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7935: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7936: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7937: ENDHEADER
1.408     albertel 7938:     my %responses;
                   7939:     my @questiontitles;
1.405     www      7940:     my $errormsg='';
                   7941:     my $number=0;
                   7942:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7943: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7944:     }
1.419     www      7945:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7946:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7947:     }
1.411     www      7948:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7949:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.443     banghart 7950:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
                   7951:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.411     www      7952:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7953:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7954:              '<br />';
1.414     www      7955: # Remember Question Titles
                   7956: # FIXME: Possibly need delimiter other than ":"
                   7957:     for (my $i=0;$i<$number;$i++) {
                   7958:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7959:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7960:     }
1.411     www      7961:     my $correct_count=0;
                   7962:     my $student_count=0;
                   7963:     my $unknown_count=0;
1.414     www      7964: # Match answers with usernames
                   7965: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7966:     foreach my $id (keys(%responses)) {
1.410     www      7967:        if ($correct_ids{$id}) {
1.414     www      7968:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7969:           $correct_count++;
1.410     www      7970:        } elsif ($clicker_ids{$id}) {
1.437     www      7971:           if ($clicker_ids{$id}=~/\,/) {
                   7972: # More than one user with the same clicker!
                   7973:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   7974:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7975:                            "<select name='multi".$id."'>";
                   7976:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   7977:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   7978:              }
                   7979:              $result.='</select>';
                   7980:              $unknown_count++;
                   7981:           } else {
                   7982: # Good: found one and only one user with the right clicker
                   7983:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   7984:              $student_count++;
                   7985:           }
1.410     www      7986:        } else {
1.411     www      7987:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7988:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7989:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7990:                    "\n".&mt("Domain").": ".
                   7991:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7992:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7993:           $unknown_count++;
1.410     www      7994:        }
1.405     www      7995:     }
1.412     www      7996:     $result.='<hr />'.
                   7997:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7998:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7999:        if ($correct_count==0) {
                   8000:           $errormsg.="Found no correct answers answers for grading!";
                   8001:        } elsif ($correct_count>1) {
1.414     www      8002:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8003:        }
                   8004:     }
1.428     www      8005:     if ($number<1) {
                   8006:        $errormsg.="Found no questions.";
                   8007:     }
1.412     www      8008:     if ($errormsg) {
                   8009:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8010:     } else {
                   8011:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8012:     }
                   8013:     $result.='</form></td></tr></table>'."\n".
1.410     www      8014:              '</td></tr></table><br /><br />'."\n";
1.404     www      8015:     return $result.&show_grading_menu_form($symb);
1.400     www      8016: }
                   8017: 
1.405     www      8018: sub iclicker_eval {
1.406     www      8019:     my ($questiontitles,$responses)=@_;
1.405     www      8020:     my $number=0;
                   8021:     my $errormsg='';
                   8022:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8023:         my %components=&Apache::loncommon::record_sep($line);
                   8024:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8025: 	if ($entries[0] eq 'Question') {
                   8026: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8027: 		$$questiontitles[$number]=$entries[$i];
                   8028: 		$number++;
                   8029: 	    }
                   8030: 	}
                   8031: 	if ($entries[0]=~/^\#/) {
                   8032: 	    my $id=$entries[0];
                   8033: 	    my @idresponses;
                   8034: 	    $id=~s/^[\#0]+//;
                   8035: 	    for (my $i=0;$i<$number;$i++) {
                   8036: 		my $idx=3+$i*6;
                   8037: 		push(@idresponses,$entries[$idx]);
                   8038: 	    }
                   8039: 	    $$responses{$id}=join(',',@idresponses);
                   8040: 	}
1.405     www      8041:     }
                   8042:     return ($errormsg,$number);
                   8043: }
                   8044: 
1.419     www      8045: sub interwrite_eval {
                   8046:     my ($questiontitles,$responses)=@_;
                   8047:     my $number=0;
                   8048:     my $errormsg='';
1.420     www      8049:     my $skipline=1;
                   8050:     my $questionnumber=0;
                   8051:     my %idresponses=();
1.419     www      8052:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   8053:         my %components=&Apache::loncommon::record_sep($line);
                   8054:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      8055:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   8056:         if ($entries[1] eq 'Response') { $skipline=1; }
                   8057:         next if $skipline;
                   8058:         if ($entries[0]!=$questionnumber) {
                   8059:            $questionnumber=$entries[0];
                   8060:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   8061:            $number++;
1.419     www      8062:         }
1.420     www      8063:         my $id=$entries[4];
                   8064:         $id=~s/^[\#0]+//;
1.421     www      8065:         $id=~s/^v\d*\://i;
                   8066:         $id=~s/[\-\:]//g;
1.420     www      8067:         $idresponses{$id}[$number]=$entries[6];
                   8068:     }
                   8069:     foreach my $id (keys %idresponses) {
                   8070:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   8071:        $$responses{$id}=~s/^\s*\,//;
1.419     www      8072:     }
                   8073:     return ($errormsg,$number);
                   8074: }
                   8075: 
1.414     www      8076: sub assign_clicker_grades {
                   8077:     my ($r)=@_;
                   8078:     my ($symb)=&get_symb($r);
                   8079:     if (!$symb) {return '';}
1.416     www      8080: # See which part we are saving to
                   8081:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   8082: # FIXME: This should probably look for the first handgradeable part
                   8083:     my $part=$$partlist[0];
                   8084: # Start screen output
1.414     www      8085:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      8086: 
1.414     www      8087:     my $heading=&mt('Assigning grades based on clicker file');
                   8088:     $result.=(<<ENDHEADER);
                   8089: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8090: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8091: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8092: ENDHEADER
                   8093: # Get correct result
                   8094: # FIXME: Possibly need delimiter other than ":"
                   8095:     my @correct=();
1.415     www      8096:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   8097:     my $number=$env{'form.number'};
                   8098:     if ($gradingmechanism ne 'attendance') {
1.414     www      8099:        foreach my $key (keys(%env)) {
                   8100:           if ($key=~/^form\.correct\:/) {
                   8101:              my @input=split(/\,/,$env{$key});
                   8102:              for (my $i=0;$i<=$#input;$i++) {
                   8103:                  if (($correct[$i]) && ($input[$i]) &&
                   8104:                      ($correct[$i] ne $input[$i])) {
                   8105:                     $result.='<br /><span class="LC_warning">'.
                   8106:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   8107:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   8108:                  } elsif ($input[$i]) {
                   8109:                     $correct[$i]=$input[$i];
                   8110:                  }
                   8111:              }
                   8112:           }
                   8113:        }
1.415     www      8114:        for (my $i=0;$i<$number;$i++) {
1.414     www      8115:           if (!$correct[$i]) {
                   8116:              $result.='<br /><span class="LC_error">'.
                   8117:                       &mt('No correct result given for question "[_1]"!',
                   8118:                           $env{'form.question:'.$i}).'</span>';
                   8119:           }
                   8120:        }
                   8121:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   8122:     }
                   8123: # Start grading
1.415     www      8124:     my $pcorrect=$env{'form.pcorrect'};
                   8125:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      8126:     my $storecount=0;
1.415     www      8127:     foreach my $key (keys(%env)) {
1.420     www      8128:        my $user='';
1.415     www      8129:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      8130:           $user=$1;
                   8131:        }
                   8132:        if ($key=~/^form\.unknown\:(.*)$/) {
                   8133:           my $id=$1;
                   8134:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   8135:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      8136:           } elsif ($env{'form.multi'.$id}) {
                   8137:              $user=$env{'form.multi'.$id};
1.420     www      8138:           }
                   8139:        }
                   8140:        if ($user) { 
1.415     www      8141:           my @answer=split(/\,/,$env{$key});
                   8142:           my $sum=0;
                   8143:           for (my $i=0;$i<$number;$i++) {
                   8144:              if ($answer[$i]) {
                   8145:                 if ($gradingmechanism eq 'attendance') {
                   8146:                    $sum+=$pcorrect;
                   8147:                 } else {
                   8148:                    if ($answer[$i] eq $correct[$i]) {
                   8149:                       $sum+=$pcorrect;
                   8150:                    } else {
                   8151:                       $sum+=$pincorrect;
                   8152:                    }
                   8153:                 }
                   8154:              }
                   8155:           }
1.416     www      8156:           my $ave=$sum/(100*$number);
                   8157: # Store
                   8158:           my ($username,$domain)=split(/\:/,$user);
                   8159:           my %grades=();
                   8160:           $grades{"resource.$part.solved"}='correct_by_override';
                   8161:           $grades{"resource.$part.awarded"}=$ave;
                   8162:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   8163:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   8164:                                                  $env{'request.course.id'},
                   8165:                                                  $domain,$username);
                   8166:           if ($returncode ne 'ok') {
                   8167:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   8168:           } else {
                   8169:              $storecount++;
                   8170:           }
1.415     www      8171:        }
                   8172:     }
                   8173: # We are done
1.416     www      8174:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   8175:              '</td></tr></table>'."\n".
1.414     www      8176:              '</td></tr></table><br /><br />'."\n";
                   8177:     return $result.&show_grading_menu_form($symb);
                   8178: }
                   8179: 
1.1       albertel 8180: sub handler {
1.41      ng       8181:     my $request=$_[0];
1.434     albertel 8182:     &reset_caches();
1.257     albertel 8183:     if ($env{'browser.mathml'}) {
1.141     www      8184: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8185:     } else {
1.141     www      8186: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8187:     }
                   8188:     $request->send_http_header;
1.44      ng       8189:     return '' if $request->header_only;
1.41      ng       8190:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8191:     my $symb=&get_symb($request,1);
1.160     albertel 8192:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8193:     my $command=$commands[0];
1.447     foxr     8194: 
1.160     albertel 8195:     if ($#commands > 0) {
                   8196: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8197:     }
1.447     foxr     8198: 
                   8199: 
1.353     albertel 8200:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 8201:     if ($symb eq '' && $command eq '') {
1.257     albertel 8202: 	if ($env{'user.adv'}) {
                   8203: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   8204: 		($env{'form.codethree'})) {
                   8205: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   8206: 		    $env{'form.codethree'};
1.41      ng       8207: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   8208: 		    &Apache::lonnet::checkin($token);
                   8209: 		if ($tsymb) {
1.137     albertel 8210: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       8211: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 8212: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   8213: 					  ('grade_username' => $tuname,
                   8214: 					   'grade_domain' => $tudom,
                   8215: 					   'grade_courseid' => $tcrsid,
                   8216: 					   'grade_symb' => $tsymb)));
1.41      ng       8217: 		    } else {
1.45      ng       8218: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 8219: 		    }
1.41      ng       8220: 		} else {
1.45      ng       8221: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       8222: 		}
1.14      www      8223: 	    } else {
1.41      ng       8224: 		$request->print(&Apache::lonxml::tokeninputfield());
                   8225: 	    }
                   8226: 	}
                   8227:     } else {
1.285     albertel 8228: 	&init_perm();
1.104     albertel 8229: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 8230: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 8231: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       8232: 	    &pickStudentPage($request);
1.103     albertel 8233: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       8234: 	    &displayPage($request);
1.104     albertel 8235: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       8236: 	    &updateGradeByPage($request);
1.104     albertel 8237: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       8238: 	    &processGroup($request);
1.104     albertel 8239: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 8240: 	    $request->print(&grading_menu($request));
                   8241: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   8242: 	    $request->print(&submit_options($request));
1.104     albertel 8243: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       8244: 	    $request->print(&viewgrades($request));
1.104     albertel 8245: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       8246: 	    $request->print(&processHandGrade($request));
1.106     albertel 8247: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       8248: 	    $request->print(&editgrades($request));
1.106     albertel 8249: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       8250: 	    $request->print(&verifyreceipt($request));
1.400     www      8251:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   8252:             $request->print(&process_clicker($request));
                   8253:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   8254:             $request->print(&process_clicker_file($request));
1.414     www      8255:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   8256:             $request->print(&assign_clicker_grades($request));
1.106     albertel 8257: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       8258: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 8259: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       8260: 	    $request->print(&csvupload($request));
1.106     albertel 8261: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       8262: 	    $request->print(&csvuploadmap($request));
1.246     albertel 8263: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 8264: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 8265: 		$request->print(&csvuploadoptions($request));
1.41      ng       8266: 	    } else {
1.257     albertel 8267: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   8268: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       8269: 		} else {
1.257     albertel 8270: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       8271: 		}
                   8272: 		$request->print(&csvuploadmap($request));
                   8273: 	    }
1.246     albertel 8274: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   8275: 	    $request->print(&csvuploadassign($request));
1.106     albertel 8276: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 8277: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 8278:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   8279:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 8280: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   8281: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 8282: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 8283: 	    $request->print(&scantron_process_students($request));
1.157     albertel 8284:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 8285:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8286: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 8287:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 8288:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 8289:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8290: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 8291:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 8292:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 8293: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 8294:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 8295: 	} elsif ($command) {
1.157     albertel 8296: 	    $request->print("Access Denied ($command)");
1.26      albertel 8297: 	}
1.2       albertel 8298:     }
1.353     albertel 8299:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 8300:     &reset_caches();
1.44      ng       8301:     return '';
                   8302: }
                   8303: 
1.1       albertel 8304: 1;
                   8305: 
1.13      albertel 8306: __END__;

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