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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.441   ! www         4: # $Id: grades.pm,v 1.440 2007/09/10 23:03:35 albertel Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: package Apache::grades;
                     30: use strict;
                     31: use Apache::style;
                     32: use Apache::lonxml;
                     33: use Apache::lonnet;
1.3       albertel   34: use Apache::loncommon;
1.112     ng         35: use Apache::lonhtmlcommon;
1.68      ng         36: use Apache::lonnavmaps;
1.1       albertel   37: use Apache::lonhomework;
1.55      matthew    38: use Apache::loncoursedata;
1.362     albertel   39: use Apache::lonmsg();
1.1       albertel   40: use Apache::Constants qw(:common);
1.167     sakharuk   41: use Apache::lonlocal;
1.386     raeburn    42: use Apache::lonenc;
1.170     albertel   43: use String::Similarity;
1.359     www        44: use LONCAPA;
                     45: 
1.315     bowersj2   46: use POSIX qw(floor);
1.87      www        47: 
1.435     foxr       48: 
                     49: my %perm=();
                     50: my %bubble_lines_per_response;     # no. bubble lines for each response.
                     51:                                    # index is "symb.part_id"
                     52: 
1.1       albertel   53: 
1.68      ng         54: # ----- These first few routines are general use routines.----
1.44      ng         55: #
1.146     albertel   56: # --- Retrieve the parts from the metadata file.---
1.44      ng         57: sub getpartlist {
1.324     albertel   58:     my ($symb) = @_;
1.439     albertel   59: 
                     60:     my $navmap   = Apache::lonnavmaps::navmap->new();
                     61:     my $res      = $navmap->getBySymb($symb);
                     62:     my $partlist = $res->parts();
                     63:     my $url      = $res->src();
                     64:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                     65: 
1.146     albertel   66:     my @stores;
1.439     albertel   67:     foreach my $part (@{ $partlist }) {
1.146     albertel   68: 	foreach my $key (@metakeys) {
                     69: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                     70: 	}
                     71:     }
                     72:     return @stores;
1.2       albertel   73: }
                     74: 
1.44      ng         75: # --- Get the symbolic name of a problem and the url
1.324     albertel   76: sub get_symb {
1.173     albertel   77:     my ($request,$silent) = @_;
1.257     albertel   78:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                     79:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel   80:     if ($symb eq '') { 
                     81: 	if (!$silent) {
                     82: 	    $request->print("Unable to handle ambiguous references:$url:.");
                     83: 	    return ();
                     84: 	}
                     85:     }
1.418     albertel   86:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel   87:     return ($symb);
1.32      ng         88: }
                     89: 
1.129     ng         90: #--- Format fullname, username:domain if different for display
                     91: #--- Use anywhere where the student names are listed
                     92: sub nameUserString {
                     93:     my ($type,$fullname,$uname,$udom) = @_;
                     94:     if ($type eq 'header') {
1.398     albertel   95: 	return '<b>&nbsp;Fullname&nbsp;</b><span class="LC_internal_info">(Username)</span>';
1.129     ng         96:     } else {
1.398     albertel   97: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                     98: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng         99:     }
                    100: }
                    101: 
1.44      ng        102: #--- Get the partlist and the response type for a given problem. ---
                    103: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        104: sub response_type {
1.324     albertel  105:     my ($symb) = shift;
1.377     albertel  106: 
                    107:     my $navmap = Apache::lonnavmaps::navmap->new();
                    108:     my $res = $navmap->getBySymb($symb);
                    109:     my $partlist = $res->parts();
1.392     albertel  110:     my %vPart = 
                    111: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  112:     my (%response_types,%handgrade);
                    113:     foreach my $part (@{ $partlist }) {
1.392     albertel  114: 	next if (%vPart && !exists($vPart{$part}));
                    115: 
1.377     albertel  116: 	my @types = $res->responseType($part);
                    117: 	my @ids = $res->responseIds($part);
                    118: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    119: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    120: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    121: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    122: 				     '.handgrade',$symb);
1.41      ng        123: 	}
                    124:     }
1.377     albertel  125:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        126: }
                    127: 
1.375     albertel  128: sub flatten_responseType {
                    129:     my ($responseType) = @_;
                    130:     my @part_response_id =
                    131: 	map { 
                    132: 	    my $part = $_;
                    133: 	    map {
                    134: 		[$part,$_]
                    135: 		} sort(keys(%{ $responseType->{$part} }));
                    136: 	} sort(keys(%$responseType));
                    137:     return @part_response_id;
                    138: }
                    139: 
1.207     albertel  140: sub get_display_part {
1.324     albertel  141:     my ($partID,$symb)=@_;
1.207     albertel  142:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    143:     if (defined($display) and $display ne '') {
1.398     albertel  144: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  145:     } else {
                    146: 	$display=$partID;
                    147:     }
                    148:     return $display;
                    149: }
1.269     raeburn   150: 
1.118     ng        151: #--- Show resource title
                    152: #--- and parts and response type
                    153: sub showResourceInfo {
1.324     albertel  154:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  155:     my $col=3;
                    156:     if ($checkboxes) { $col=4; }
1.398     albertel  157:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    158:     $result .='<table border="0">';
1.324     albertel  159:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        160:     my %resptype = ();
1.122     ng        161:     my $hdgrade='no';
1.154     albertel  162:     my %partsseen;
1.375     albertel  163:     foreach my $partID (sort keys(%$responseType)) {
                    164: 	foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
                    165: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    166: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    167: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    168: 	    $result.='<tr>';
                    169: 	    if ($checkboxes) {
                    170: 		if (exists($partsseen{$partID})) {
                    171: 		    $result.="<td>&nbsp;</td>";
                    172: 		} else {
1.401     albertel  173: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  174: 		}
                    175: 		$partsseen{$partID}=1;
1.154     albertel  176: 	    }
1.375     albertel  177: 	    my $display_part=&get_display_part($partID,$symb);
1.398     albertel  178: 	    $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
                    179: 		$resID.'</span></td>'.
1.375     albertel  180: 		'<td><b>Type: </b>'.$responsetype.'</td></tr>';
                    181: #	    '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
1.154     albertel  182: 	}
1.118     ng        183:     }
                    184:     $result.='</table>'."\n";
1.147     albertel  185:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        186: }
                    187: 
1.434     albertel  188: sub reset_caches {
                    189:     &reset_analyze_cache();
                    190:     &reset_perm();
                    191: }
                    192: 
                    193: {
                    194:     my %analyze_cache;
1.148     albertel  195: 
1.434     albertel  196:     sub reset_analyze_cache {
                    197: 	undef(%analyze_cache);
                    198:     }
                    199: 
                    200:     sub get_analyze {
                    201: 	my ($symb,$uname,$udom)=@_;
                    202: 	my $key = "$symb\0$uname\0$udom";
                    203: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
                    204: 
                    205: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    206: 	$url=&Apache::lonnet::clutter($url);
                    207: 	my $subresult=&Apache::lonnet::ssi($url,
                    208: 					   ('grade_target' => 'analyze'),
                    209: 					   ('grade_domain' => $udom),
                    210: 					   ('grade_symb' => $symb),
                    211: 					   ('grade_courseid' => 
                    212: 					    $env{'request.course.id'}),
                    213: 					   ('grade_username' => $uname));
                    214: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    215: 	my %analyze=&Apache::lonnet::str2hash($subresult);
                    216: 	return $analyze_cache{$key} = \%analyze;
                    217:     }
                    218: 
                    219:     sub get_order {
                    220: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    221: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    222: 	return $analyze->{"$partid.$respid.shown"};
                    223:     }
                    224: 
                    225:     sub get_radiobutton_correct_foil {
                    226: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    227: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    228: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
                    229: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    230: 		return $foil;
                    231: 	    }
                    232: 	}
                    233:     }
1.148     albertel  234: }
1.434     albertel  235: 
1.118     ng        236: #--- Clean response type for display
1.335     albertel  237: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    238: #        response types only.
1.118     ng        239: sub cleanRecord {
1.336     albertel  240:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    241: 	$uname,$udom) = @_;
1.398     albertel  242:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  243:     if ($response =~ /^(option|rank)$/) {
                    244: 	my %answer=&Apache::lonnet::str2hash($answer);
                    245: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    246: 	my ($toprow,$bottomrow);
                    247: 	foreach my $foil (@$order) {
                    248: 	    if ($grading{$foil} == 1) {
                    249: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    250: 	    } else {
                    251: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    252: 	    }
1.398     albertel  253: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  254: 	}
                    255: 	return '<blockquote><table border="1">'.
                    256: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  257: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  258: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    259:     } elsif ($response eq 'match') {
                    260: 	my %answer=&Apache::lonnet::str2hash($answer);
                    261: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    262: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    263: 	my ($toprow,$middlerow,$bottomrow);
                    264: 	foreach my $foil (@$order) {
                    265: 	    my $item=shift(@items);
                    266: 	    if ($grading{$foil} == 1) {
                    267: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  268: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  269: 	    } else {
                    270: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  271: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  272: 	    }
1.398     albertel  273: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        274: 	}
1.126     ng        275: 	return '<blockquote><table border="1">'.
1.148     albertel  276: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  277: 	    '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
1.148     albertel  278: 	    $middlerow.'</tr>'.
1.398     albertel  279: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  280: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    281:     } elsif ($response eq 'radiobutton') {
                    282: 	my %answer=&Apache::lonnet::str2hash($answer);
                    283: 	my ($toprow,$bottomrow);
1.434     albertel  284: 	my $correct = 
                    285: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    286: 	foreach my $foil (@$order) {
1.148     albertel  287: 	    if (exists($answer{$foil})) {
1.434     albertel  288: 		if ($foil eq $correct) {
1.148     albertel  289: 		    $toprow.='<td><b>true</b></td>';
                    290: 		} else {
                    291: 		    $toprow.='<td><i>true</i></td>';
                    292: 		}
                    293: 	    } else {
                    294: 		$toprow.='<td>false</td>';
                    295: 	    }
1.398     albertel  296: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  297: 	}
                    298: 	return '<blockquote><table border="1">'.
                    299: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  300: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  301: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    302:     } elsif ($response eq 'essay') {
1.257     albertel  303: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        304: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  305: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    306: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        307: 
1.257     albertel  308: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    309: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    310: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    311: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    312: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    313: 	    $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        314: 	}
1.166     albertel  315: 	$answer =~ s-\n-<br />-g;
                    316: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  317:     } elsif ( $response eq 'organic') {
                    318: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    319: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    320: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    321: 	return $result;
1.335     albertel  322:     } elsif ( $response eq 'Task') {
                    323: 	if ( $answer eq 'SUBMITTED') {
                    324: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  325: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  326: 	    return $result;
                    327: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    328: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    329: 			       keys(%{$record}));
                    330: 	    return join('<br />',($version,@matches));
                    331: 			       
                    332: 			       
                    333: 	} else {
                    334: 	    my $result =
                    335: 		'<p>'
                    336: 		.&mt('Overall result: [_1]',
                    337: 		     $record->{$version."resource.$respid.$partid.status"})
                    338: 		.'</p>';
                    339: 	    
                    340: 	    $result .= '<ul>';
                    341: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    342: 			     keys(%{$record}));
                    343: 	    foreach my $grade (sort(@grade)) {
                    344: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    345: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    346: 				     $dim, $record->{$grade}).
                    347: 			  '</li>';
                    348: 	    }
                    349: 	    $result.='</ul>';
                    350: 	    return $result;
                    351: 	}
1.440     albertel  352:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    353: 	$answer = 
                    354: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    355: 							      $answer);
1.122     ng        356:     }
1.118     ng        357:     return $answer;
                    358: }
                    359: 
                    360: #-- A couple of common js functions
                    361: sub commonJSfunctions {
                    362:     my $request = shift;
                    363:     $request->print(<<COMMONJSFUNCTIONS);
                    364: <script type="text/javascript" language="javascript">
                    365:     function radioSelection(radioButton) {
                    366: 	var selection=null;
                    367: 	if (radioButton.length > 1) {
                    368: 	    for (var i=0; i<radioButton.length; i++) {
                    369: 		if (radioButton[i].checked) {
                    370: 		    return radioButton[i].value;
                    371: 		}
                    372: 	    }
                    373: 	} else {
                    374: 	    if (radioButton.checked) return radioButton.value;
                    375: 	}
                    376: 	return selection;
                    377:     }
                    378: 
                    379:     function pullDownSelection(selectOne) {
                    380: 	var selection="";
                    381: 	if (selectOne.length > 1) {
                    382: 	    for (var i=0; i<selectOne.length; i++) {
                    383: 		if (selectOne[i].selected) {
                    384: 		    return selectOne[i].value;
                    385: 		}
                    386: 	    }
                    387: 	} else {
1.138     albertel  388:             // only one value it must be the selected one
                    389: 	    return selectOne.value;
1.118     ng        390: 	}
                    391:     }
                    392: </script>
                    393: COMMONJSFUNCTIONS
                    394: }
                    395: 
1.44      ng        396: #--- Dumps the class list with usernames,list of sections,
                    397: #--- section, ids and fullnames for each user.
                    398: sub getclasslist {
1.76      ng        399:     my ($getsec,$filterlist) = @_;
1.291     albertel  400:     my @getsec;
                    401:     if (!ref($getsec)) {
                    402: 	if ($getsec ne '' && $getsec ne 'all') {
                    403: 	    @getsec=($getsec);
                    404: 	}
                    405:     } else {
                    406: 	@getsec=@{$getsec};
                    407:     }
                    408:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
                    409: 
1.56      matthew   410:     my $classlist=&Apache::loncoursedata::get_classlist();
1.49      albertel  411:     # Bail out if we were unable to get the classlist
1.56      matthew   412:     return if (! defined($classlist));
                    413:     #
                    414:     my %sections;
                    415:     my %fullnames;
1.205     matthew   416:     foreach my $student (keys(%$classlist)) {
                    417:         my $end      = 
                    418:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    419:         my $start    = 
                    420:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    421:         my $id       = 
                    422:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    423:         my $section  = 
                    424:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    425:         my $fullname = 
                    426:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    427:         my $status   = 
                    428:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.76      ng        429: 	# filter students according to status selected
1.257     albertel  430: 	if ($filterlist && $env{'form.Status'} ne 'Any') {
                    431: 	    if ($env{'form.Status'} ne $status) {
1.205     matthew   432: 		delete ($classlist->{$student});
1.76      ng        433: 		next;
                    434: 	    }
                    435: 	}
1.205     matthew   436: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  437: 	if (&canview($section)) {
1.291     albertel  438: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  439: 		$sections{$section}++;
1.205     matthew   440: 		$fullnames{$student}=$fullname;
1.103     albertel  441: 	    } else {
1.205     matthew   442: 		delete($classlist->{$student});
1.103     albertel  443: 	    }
                    444: 	} else {
1.205     matthew   445: 	    delete($classlist->{$student});
1.103     albertel  446: 	}
1.44      ng        447:     }
                    448:     my %seen = ();
1.56      matthew   449:     my @sections = sort(keys(%sections));
                    450:     return ($classlist,\@sections,\%fullnames);
1.44      ng        451: }
                    452: 
1.103     albertel  453: sub canmodify {
                    454:     my ($sec)=@_;
                    455:     if ($perm{'mgr'}) {
                    456: 	if (!defined($perm{'mgr_section'})) {
                    457: 	    # can modify whole class
                    458: 	    return 1;
                    459: 	} else {
                    460: 	    if ($sec eq $perm{'mgr_section'}) {
                    461: 		#can modify the requested section
                    462: 		return 1;
                    463: 	    } else {
                    464: 		# can't modify the request section
                    465: 		return 0;
                    466: 	    }
                    467: 	}
                    468:     }
                    469:     #can't modify
                    470:     return 0;
                    471: }
                    472: 
                    473: sub canview {
                    474:     my ($sec)=@_;
                    475:     if ($perm{'vgr'}) {
                    476: 	if (!defined($perm{'vgr_section'})) {
                    477: 	    # can modify whole class
                    478: 	    return 1;
                    479: 	} else {
                    480: 	    if ($sec eq $perm{'vgr_section'}) {
                    481: 		#can modify the requested section
                    482: 		return 1;
                    483: 	    } else {
                    484: 		# can't modify the request section
                    485: 		return 0;
                    486: 	    }
                    487: 	}
                    488:     }
                    489:     #can't modify
                    490:     return 0;
                    491: }
                    492: 
1.44      ng        493: #--- Retrieve the grade status of a student for all the parts
                    494: sub student_gradeStatus {
1.324     albertel  495:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  496:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        497:     my %partstatus = ();
                    498:     foreach (@$partlist) {
1.128     ng        499: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        500: 	$status              = 'nothing' if ($status eq '');
                    501: 	$partstatus{$_}      = $status;
                    502: 	my $subkey           = "resource.$_.submitted_by";
                    503: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    504:     }
                    505:     return %partstatus;
                    506: }
                    507: 
1.45      ng        508: # hidden form and javascript that calls the form
                    509: # Use by verifyscript and viewgrades
                    510: # Shows a student's view of problem and submission
                    511: sub jscriptNform {
1.324     albertel  512:     my ($symb) = @_;
1.45      ng        513:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    514: 	'    function viewOneStudent(user,domain) {'."\n".
                    515: 	'	document.onestudent.student.value = user;'."\n".
                    516: 	'	document.onestudent.userdom.value = domain;'."\n".
                    517: 	'	document.onestudent.submit();'."\n".
                    518: 	'    }'."\n".
                    519: 	'</script>'."\n";
                    520:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  521: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  522: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    523: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
                    524: 	'<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.45      ng        525: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    526: 	'<input type="hidden" name="student" value="" />'."\n".
                    527: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    528: 	'</form>'."\n";
                    529:     return $jscript;
                    530: }
1.39      ng        531: 
1.315     bowersj2  532: # Given the score (as a number [0-1] and the weight) what is the final
                    533: # point value? This function will round to the nearest tenth, third,
                    534: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  535: sub compute_points {
1.315     bowersj2  536:     my ($score, $weight) = @_;
                    537:     
                    538:     my $tolerance = .00001;
                    539:     my $points = $score * $weight;
                    540: 
                    541:     # Check for nearness to 1/x.
                    542:     my $check_for_nearness = sub {
                    543:         my ($factor) = @_;
                    544:         my $num = ($points * $factor) + $tolerance;
                    545:         my $floored_num = floor($num);
1.316     albertel  546:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  547:             return $floored_num / $factor;
                    548:         }
                    549:         return $points;
                    550:     };
                    551: 
                    552:     $points = $check_for_nearness->(10);
                    553:     $points = $check_for_nearness->(3);
                    554:     $points = $check_for_nearness->(4);
                    555:     
                    556:     return $points;
                    557: }
                    558: 
1.44      ng        559: #------------------ End of general use routines --------------------
1.87      www       560: 
                    561: #
                    562: # Find most similar essay
                    563: #
                    564: 
                    565: sub most_similar {
1.426     albertel  566:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       567: 
                    568: # ignore spaces and punctuation
                    569: 
                    570:     $uessay=~s/\W+/ /gs;
                    571: 
1.282     www       572: # ignore empty submissions (occuring when only files are sent)
                    573: 
                    574:     unless ($uessay=~/\w+/) { return ''; }
                    575: 
1.87      www       576: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       577:     my $limit=0.6;
1.87      www       578:     my $sname='';
                    579:     my $sdom='';
                    580:     my $scrsid='';
                    581:     my $sessay='';
                    582: # go through all essays ...
1.426     albertel  583:     foreach my $tkey (keys(%$old_essays)) {
                    584: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       585: # ... except the same student
1.426     albertel  586:         next if (($tname eq $uname) && ($tdom eq $udom));
                    587: 	my $tessay=$old_essays->{$tkey};
                    588: 	$tessay=~s/\W+/ /gs;
1.87      www       589: # String similarity gives up if not even limit
1.426     albertel  590: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       591: # Found one
1.426     albertel  592: 	if ($tsimilar>$limit) {
                    593: 	    $limit=$tsimilar;
                    594: 	    $sname=$tname;
                    595: 	    $sdom=$tdom;
                    596: 	    $scrsid=$tcrsid;
                    597: 	    $sessay=$old_essays->{$tkey};
                    598: 	}
1.87      www       599:     }
1.88      www       600:     if ($limit>0.6) {
1.87      www       601:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    602:     } else {
                    603:        return ('','','','',0);
                    604:     }
                    605: }
                    606: 
1.44      ng        607: #-------------------------------------------------------------------
                    608: 
                    609: #------------------------------------ Receipt Verification Routines
1.45      ng        610: #
1.44      ng        611: #--- Check whether a receipt number is valid.---
                    612: sub verifyreceipt {
                    613:     my $request  = shift;
                    614: 
1.257     albertel  615:     my $courseid = $env{'request.course.id'};
1.184     www       616:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  617: 	$env{'form.receipt'};
1.44      ng        618:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  619:     my ($symb)   = &get_symb($request);
1.44      ng        620: 
1.398     albertel  621:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
                    622: 	$receipt.'</h3></span>'."\n".
                    623: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
1.44      ng        624: 
                    625:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   626:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  627:     
                    628:     my $receiptparts=0;
1.390     albertel  629:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    630: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  631:     my $parts=['0'];
1.324     albertel  632:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.294     albertel  633:     foreach (sort 
                    634: 	     {
                    635: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    636: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    637: 		 }
                    638: 		 return $a cmp $b;
                    639: 	     } (keys(%$fullname))) {
1.44      ng        640: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  641: 	foreach my $part (@$parts) {
                    642: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
                    643: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
                    644: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  645: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  646: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    647: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    648: 		if ($receiptparts) {
                    649: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    650: 		}
                    651: 		$contents.='</tr>'."\n";
                    652: 		
                    653: 		$matches++;
                    654: 	    }
1.44      ng        655: 	}
                    656:     }
                    657:     if ($matches == 0) {
                    658: 	$string = $title.'No match found for the above receipt.';
                    659:     } else {
1.324     albertel  660: 	$string = &jscriptNform($symb).$title.
1.44      ng        661: 	    'The above receipt matches the following student'.
                    662: 	    ($matches <= 1 ? '.' : 's.')."\n".
                    663: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                    664: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
                    665: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
                    666: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
1.177     albertel  667: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
                    668: 	if ($receiptparts) {
                    669: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
                    670: 	}
                    671: 	$string.='</tr>'."\n".$contents.
1.44      ng        672: 	    '</table></td></tr></table>'."\n";
                    673:     }
1.324     albertel  674:     return $string.&show_grading_menu_form($symb);
1.44      ng        675: }
                    676: 
                    677: #--- This is called by a number of programs.
                    678: #--- Called from the Grading Menu - View/Grade an individual student
                    679: #--- Also called directly when one clicks on the subm button 
                    680: #    on the problem page.
1.30      ng        681: sub listStudents {
1.41      ng        682:     my ($request) = shift;
1.49      albertel  683: 
1.324     albertel  684:     my ($symb) = &get_symb($request);
1.257     albertel  685:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    686:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    687:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                    688:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    689: 
                    690:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    691:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    692: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  693: 
1.398     albertel  694:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
                    695: 	' Submissions for a Student or a Group of Students</span></h3>';
1.118     ng        696: 
1.324     albertel  697:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  698: 
1.45      ng        699:     $request->print(<<LISTJAVASCRIPT);
                    700: <script type="text/javascript" language="javascript">
1.110     ng        701:     function checkSelect(checkBox) {
                    702: 	var ctr=0;
                    703: 	var sense="";
                    704: 	if (checkBox.length > 1) {
                    705: 	    for (var i=0; i<checkBox.length; i++) {
                    706: 		if (checkBox[i].checked) {
                    707: 		    ctr++;
                    708: 		}
                    709: 	    }
                    710: 	    sense = "a student or group of students";
                    711: 	} else {
                    712: 	    if (checkBox.checked) {
                    713: 		ctr = 1;
                    714: 	    }
                    715: 	    sense = "the student";
                    716: 	}
                    717: 	if (ctr == 0) {
1.126     ng        718: 	    alert("Please select "+sense+" before clicking on the Next button.");
1.110     ng        719: 	    return false;
                    720: 	}
                    721: 	document.gradesub.submit();
                    722:     }
                    723: 
                    724:     function reLoadList(formname) {
1.112     ng        725: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        726: 	formname.command.value = 'submission';
                    727: 	formname.submit();
                    728:     }
1.45      ng        729: </script>
                    730: LISTJAVASCRIPT
                    731: 
1.118     ng        732:     &commonJSfunctions($request);
1.41      ng        733:     $request->print($result);
1.39      ng        734: 
1.401     albertel  735:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    736:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  737:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
                    738: 	"\n".$table.
1.401     albertel  739: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.267     albertel  740: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
                    741: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
                    742: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
                    743: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
1.401     albertel  744: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
1.49      albertel  745: 	'&nbsp;<b>Submissions: </b>'."\n";
1.257     albertel  746:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.267     albertel  747: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
1.49      albertel  748:     }
1.110     ng        749: 
1.257     albertel  750:     my $saveStatus = $env{'form.Status'} eq '' ? 'Active' : $env{'form.Status'};
                    751:     $env{'form.Status'} = $saveStatus;
1.267     albertel  752:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
                    753: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
                    754: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
1.348     bowersj2  755: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
                    756:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
                    757:         '<option value="1">Whole Points</option>'.
                    758:         '<option value=".5">Half Points</option>'.
1.349     albertel  759:         '<option value=".25">Quarter Points</option>'.
                    760:         '<option value=".1">Tenths of a Point</option>'.
1.348     bowersj2  761:         '</select>'.
1.432     banghart  762:         &build_section_inputs().
1.45      ng        763: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  764: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    765: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    766: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    767: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  768: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        769: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    770: 
1.257     albertel  771:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
                    772: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng        773:     } else {
                    774: 	$gradeTable.='<b>Student Status:</b> '.
                    775: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
                    776:     }
1.112     ng        777: 
1.126     ng        778:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    779: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
1.110     ng        780: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  781: 
                    782: # checkall buttons
                    783:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        784:     $gradeTable.='<input type="button" '."\n".
1.45      ng        785: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.249     albertel  786: 	'value="Next->" /> <br />'."\n";
                    787:     $gradeTable.=&check_buttons();
1.401     albertel  788:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
1.249     albertel  789:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
1.45      ng        790:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
1.110     ng        791: 	'<table border="0"><tr bgcolor="#e6ffff">';
                    792:     my $loop = 0;
                    793:     while ($loop < 2) {
1.126     ng        794: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
1.250     albertel  795: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
1.301     albertel  796: 	if ($env{'form.showgrading'} eq 'yes' 
                    797: 	    && $submitonly ne 'queued'
                    798: 	    && $submitonly ne 'all') {
1.110     ng        799: 	    foreach (sort(@$partlist)) {
1.324     albertel  800: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
1.207     albertel  801: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
                    802: 		    ' Status&nbsp;</b></td>';
1.110     ng        803: 	    }
1.301     albertel  804: 	} elsif ($submitonly eq 'queued') {
                    805: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
1.110     ng        806: 	}
                    807: 	$loop++;
1.126     ng        808: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        809:     }
1.45      ng        810:     $gradeTable.='</tr>'."\n";
1.41      ng        811: 
1.45      ng        812:     my $ctr = 0;
1.294     albertel  813:     foreach my $student (sort 
                    814: 			 {
                    815: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    816: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    817: 			     }
                    818: 			     return $a cmp $b;
                    819: 			 }
                    820: 			 (keys(%$fullname))) {
1.41      ng        821: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  822: 
1.110     ng        823: 	my %status = ();
1.301     albertel  824: 
                    825: 	if ($submitonly eq 'queued') {
                    826: 	    my %queue_status = 
                    827: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    828: 							$udom,$uname);
                    829: 	    next if (!defined($queue_status{'gradingqueue'}));
                    830: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    831: 	}
                    832: 
                    833: 	if ($env{'form.showgrading'} eq 'yes' 
                    834: 	    && $submitonly ne 'queued'
                    835: 	    && $submitonly ne 'all') {
1.324     albertel  836: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  837: 	    my $submitted = 0;
1.164     albertel  838: 	    my $graded = 0;
1.248     albertel  839: 	    my $incorrect = 0;
1.110     ng        840: 	    foreach (keys(%status)) {
1.145     albertel  841: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  842: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    843: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    844: 		
1.110     ng        845: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    846: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  847: 		    $submitted = 0;
1.150     albertel  848: 		    my ($part)=split(/\./,$partid);
1.110     ng        849: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  850: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        851: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    852: 		}
1.41      ng        853: 	    }
1.248     albertel  854: 	    
1.156     albertel  855: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    856: 				     $submitonly eq 'incorrect' ||
                    857: 				     $submitonly eq 'graded'));
1.248     albertel  858: 	    next if (!$graded && ($submitonly eq 'graded'));
                    859: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        860: 	}
1.34      ng        861: 
1.45      ng        862: 	$ctr++;
1.249     albertel  863: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    864: 
1.104     albertel  865: 	if ( $perm{'vgr'} eq 'F' ) {
1.110     ng        866: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
1.126     ng        867: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  868:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    869:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    870: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    871: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
                    872: 	       '&nbsp;'.$section.'</td>'."\n";
1.110     ng        873: 
1.257     albertel  874: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        875: 		foreach (sort keys(%status)) {
                    876: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  877: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        878: 		}
1.41      ng        879: 	    }
1.126     ng        880: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.110     ng        881: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
1.41      ng        882: 	}
                    883:     }
1.110     ng        884:     if ($ctr%2 ==1) {
1.126     ng        885: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel  886: 	    if ($env{'form.showgrading'} eq 'yes' 
                    887: 		&& $submitonly ne 'queued'
                    888: 		&& $submitonly ne 'all') {
1.110     ng        889: 		foreach (@$partlist) {
                    890: 		    $gradeTable.='<td>&nbsp;</td>';
                    891: 		}
1.301     albertel  892: 	    } elsif ($submitonly eq 'queued') {
                    893: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng        894: 	    }
                    895: 	$gradeTable.='</tr>';
                    896:     }
                    897: 
1.249     albertel  898:     $gradeTable.='</table></td></tr></table>'."\n".
1.45      ng        899: 	'<input type="button" '.
                    900: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng        901: 	'value="Next->" /></form>'."\n";
1.45      ng        902:     if ($ctr == 0) {
1.96      albertel  903: 	my $num_students=(scalar(keys(%$fullname)));
                    904: 	if ($num_students eq 0) {
1.398     albertel  905: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel  906: 	} else {
1.171     albertel  907: 	    my $submissions='submissions';
                    908: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                    909: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel  910: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel  911: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel  912: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel  913: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel  914: 	}
1.46      ng        915:     } elsif ($ctr == 1) {
                    916: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
1.45      ng        917:     }
1.324     albertel  918:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng        919:     $request->print($gradeTable);
1.44      ng        920:     return '';
1.10      ng        921: }
                    922: 
1.44      ng        923: #---- Called from the listStudents routine
1.249     albertel  924: 
                    925: sub check_script {
                    926:     my ($form, $type)=@_;
                    927:     my $chkallscript='<script type="text/javascript">
                    928:     function checkall() {
                    929:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    930:             ele = document.forms.'.$form.'.elements[i];
                    931:             if (ele.name == "'.$type.'") {
                    932:             document.forms.'.$form.'.elements[i].checked=true;
                    933:                                        }
                    934:         }
                    935:     }
                    936: 
                    937:     function checksec() {
                    938:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    939:             ele = document.forms.'.$form.'.elements[i];
                    940:            string = document.forms.'.$form.'.chksec.value;
                    941:            if
                    942:           (ele.value.indexOf(":::SECTION"+string)>0) {
                    943:               document.forms.'.$form.'.elements[i].checked=true;
                    944:             }
                    945:         }
                    946:     }
                    947: 
                    948: 
                    949:     function uncheckall() {
                    950:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    951:             ele = document.forms.'.$form.'.elements[i];
                    952:             if (ele.name == "'.$type.'") {
                    953:             document.forms.'.$form.'.elements[i].checked=false;
                    954:                                        }
                    955:         }
                    956:     }
                    957: 
                    958: </script>'."\n";
                    959:     return $chkallscript;
                    960: }
                    961: 
                    962: sub check_buttons {
                    963:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                    964:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                    965:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                    966:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                    967:     return $buttons;
                    968: }
                    969: 
1.44      ng        970: #     Displays the submissions for one student or a group of students
1.34      ng        971: sub processGroup {
1.41      ng        972:     my ($request)  = shift;
                    973:     my $ctr        = 0;
1.155     albertel  974:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng        975:     my $total      = scalar(@stuchecked)-1;
1.45      ng        976: 
1.396     banghart  977:     foreach my $student (@stuchecked) {
                    978: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel  979: 	$env{'form.student'}        = $uname;
                    980: 	$env{'form.userdom'}        = $udom;
                    981: 	$env{'form.fullname'}       = $fullname;
1.41      ng        982: 	&submission($request,$ctr,$total);
                    983: 	$ctr++;
                    984:     }
                    985:     return '';
1.35      ng        986: }
1.34      ng        987: 
1.44      ng        988: #------------------------------------------------------------------------------------
                    989: #
                    990: #-------------------------- Next few routines handles grading by student, essentially
                    991: #                           handles essay response type problem/part
                    992: #
                    993: #--- Javascript to handle the submission page functionality ---
                    994: sub sub_page_js {
                    995:     my $request = shift;
                    996:     $request->print(<<SUBJAVASCRIPT);
                    997: <script type="text/javascript" language="javascript">
1.71      ng        998:     function updateRadio(formname,id,weight) {
1.125     ng        999: 	var gradeBox = formname["GD_BOX"+id];
                   1000: 	var radioButton = formname["RADVAL"+id];
                   1001: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1002: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1003: 	gradeBox.value = pts;
                   1004: 	var resetbox = false;
                   1005: 	if (isNaN(pts) || pts < 0) {
                   1006: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1007: 	    for (var i=0; i<radioButton.length; i++) {
                   1008: 		if (radioButton[i].checked) {
                   1009: 		    gradeBox.value = i;
                   1010: 		    resetbox = true;
                   1011: 		}
                   1012: 	    }
                   1013: 	    if (!resetbox) {
                   1014: 		formtextbox.value = "";
                   1015: 	    }
                   1016: 	    return;
1.44      ng       1017: 	}
1.71      ng       1018: 
                   1019: 	if (pts > weight) {
                   1020: 	    var resp = confirm("You entered a value ("+pts+
                   1021: 			       ") greater than the weight for the part. Accept?");
                   1022: 	    if (resp == false) {
1.125     ng       1023: 		gradeBox.value = oldpts;
1.71      ng       1024: 		return;
                   1025: 	    }
1.44      ng       1026: 	}
1.13      albertel 1027: 
1.71      ng       1028: 	for (var i=0; i<radioButton.length; i++) {
                   1029: 	    radioButton[i].checked=false;
                   1030: 	    if (pts == i && pts != "") {
                   1031: 		radioButton[i].checked=true;
                   1032: 	    }
                   1033: 	}
                   1034: 	updateSelect(formname,id);
1.125     ng       1035: 	formname["stores"+id].value = "0";
1.41      ng       1036:     }
1.5       albertel 1037: 
1.72      ng       1038:     function writeBox(formname,id,pts) {
1.125     ng       1039: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1040: 	if (checkSolved(formname,id) == 'update') {
                   1041: 	    gradeBox.value = pts;
                   1042: 	} else {
1.125     ng       1043: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1044: 	    gradeBox.value = oldpts;
1.125     ng       1045: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1046: 	    for (var i=0; i<radioButton.length; i++) {
                   1047: 		radioButton[i].checked=false;
1.72      ng       1048: 		if (i == oldpts) {
1.71      ng       1049: 		    radioButton[i].checked=true;
                   1050: 		}
                   1051: 	    }
1.41      ng       1052: 	}
1.125     ng       1053: 	formname["stores"+id].value = "0";
1.71      ng       1054: 	updateSelect(formname,id);
                   1055: 	return;
1.41      ng       1056:     }
1.44      ng       1057: 
1.71      ng       1058:     function clearRadBox(formname,id) {
                   1059: 	if (checkSolved(formname,id) == 'noupdate') {
                   1060: 	    updateSelect(formname,id);
                   1061: 	    return;
                   1062: 	}
1.125     ng       1063: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1064: 	for (var i=0; i<gradeSelect.length; i++) {
                   1065: 	    if (gradeSelect[i].selected) {
                   1066: 		var selectx=i;
                   1067: 	    }
                   1068: 	}
1.125     ng       1069: 	var stores = formname["stores"+id];
1.71      ng       1070: 	if (selectx == stores.value) { return };
1.125     ng       1071: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1072: 	gradeBox.value = "";
1.125     ng       1073: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1074: 	for (var i=0; i<radioButton.length; i++) {
                   1075: 	    radioButton[i].checked=false;
                   1076: 	}
                   1077: 	stores.value = selectx;
                   1078:     }
1.5       albertel 1079: 
1.71      ng       1080:     function checkSolved(formname,id) {
1.125     ng       1081: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1082: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1083: 	    if (!reply) {return "noupdate";}
1.120     ng       1084: 	    formname.overRideScore.value = 'yes';
1.41      ng       1085: 	}
1.71      ng       1086: 	return "update";
1.13      albertel 1087:     }
1.71      ng       1088: 
                   1089:     function updateSelect(formname,id) {
1.125     ng       1090: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1091: 	return;
1.41      ng       1092:     }
1.33      ng       1093: 
1.121     ng       1094: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1095:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1096: 	formname.gradeOpt.value = val;
1.71      ng       1097: 	if (val == "Save & Next") {
                   1098: 	    for (i=0;i<=total;i++) {
                   1099: 		for (j=0;j<parttot;j++) {
1.125     ng       1100: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1101: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1102: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1103: 			if (points == "") {
1.125     ng       1104: 			    var name = formname["name"+i].value;
1.129     ng       1105: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1106: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1107: 					       ", part "+partid+". Continue?");
1.71      ng       1108: 			    if (resp == false) {
1.125     ng       1109: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1110: 				return false;
                   1111: 			    }
                   1112: 			}
                   1113: 		    }
                   1114: 		    
                   1115: 		}
                   1116: 	    }
                   1117: 	    
                   1118: 	}
1.121     ng       1119: 	if (val == "Grade Student") {
                   1120: 	    formname.showgrading.value = "yes";
                   1121: 	    if (formname.Status.value == "") {
                   1122: 		formname.Status.value = "Active";
                   1123: 	    }
                   1124: 	    formname.studentNo.value = total;
                   1125: 	}
1.120     ng       1126: 	formname.submit();
                   1127:     }
                   1128: 
1.71      ng       1129: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1130:     function checkSubmitPage(formname,total) {
                   1131: 	noscore = new Array(100);
                   1132: 	var ptr = 0;
                   1133: 	for (i=1;i<total;i++) {
1.125     ng       1134: 	    var partid = formname["q_"+i].value;
1.127     ng       1135: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1136: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1137: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1138: 		if (points == "" && status != "correct_by_student") {
                   1139: 		    noscore[ptr] = i;
                   1140: 		    ptr++;
                   1141: 		}
                   1142: 	    }
                   1143: 	}
                   1144: 	if (ptr != 0) {
                   1145: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1146: 	    var prolist = "";
                   1147: 	    if (ptr == 1) {
                   1148: 		prolist = noscore[0];
                   1149: 	    } else {
                   1150: 		var i = 0;
                   1151: 		while (i < ptr-1) {
                   1152: 		    prolist += noscore[i]+", ";
                   1153: 		    i++;
                   1154: 		}
                   1155: 		prolist += "and "+noscore[i];
                   1156: 	    }
                   1157: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1158: 	    if (resp == false) {
                   1159: 		return false;
                   1160: 	    }
                   1161: 	}
1.45      ng       1162: 
1.71      ng       1163: 	formname.submit();
                   1164:     }
                   1165: </script>
                   1166: SUBJAVASCRIPT
                   1167: }
1.45      ng       1168: 
1.71      ng       1169: #--- javascript for essay type problem --
                   1170: sub sub_page_kw_js {
                   1171:     my $request = shift;
1.80      ng       1172:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1173:     &commonJSfunctions($request);
1.350     albertel 1174: 
1.351     albertel 1175:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1176:     <script text="text/javascript">
                   1177:     function checkInput() {
                   1178:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1179:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1180:       var usrctr = document.msgcenter.usrctr.value;
                   1181:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1182:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1183: 
                   1184:       var msgchk = "";
                   1185:       if (document.msgcenter.subchk.checked) {
                   1186:          msgchk = "msgsub,";
                   1187:       }
                   1188:       var includemsg = 0;
                   1189:       for (var i=1; i<=nmsg; i++) {
                   1190:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1191:           var frmmsg = document.msgcenter["msg"+i];
                   1192:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1193:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1194:           showflg.value = "1";
                   1195:           var chkbox = document.msgcenter["msgn"+i];
                   1196:           if (chkbox.checked) {
                   1197:              msgchk += "savemsg"+i+",";
                   1198:              includemsg = 1;
                   1199:           }
                   1200:       }
                   1201:       if (document.msgcenter.newmsgchk.checked) {
                   1202:          msgchk += "newmsg"+usrctr;
                   1203:          includemsg = 1;
                   1204:       }
                   1205:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1206:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1207:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1208:       includemsg.value = msgchk;
                   1209: 
                   1210:       self.close()
                   1211: 
                   1212:     }
                   1213:     </script>
                   1214: INNERJS
                   1215: 
1.351     albertel 1216:     my $inner_js_highlight_central=<<INNERJS;
                   1217:  <script type="text/javascript">
                   1218:     function updateChoice(flag) {
                   1219:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1220:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1221:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1222:       opener.document.SCORE.refresh.value = "on";
                   1223:       if (opener.document.SCORE.keywords.value!=""){
                   1224:          opener.document.SCORE.submit();
                   1225:       }
                   1226:       self.close()
                   1227:     }
                   1228: </script>
                   1229: INNERJS
                   1230: 
                   1231:     my $start_page_msg_central = 
                   1232:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1233: 				       {'js_ready'  => 1,
                   1234: 					'only_body' => 1,
                   1235: 					'bgcolor'   =>'#FFFFFF',});
                   1236:     my $end_page_msg_central = 
                   1237: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1238: 
                   1239: 
                   1240:     my $start_page_highlight_central = 
                   1241:         &Apache::loncommon::start_page('Highlight Central',
                   1242: 				       $inner_js_highlight_central,
1.350     albertel 1243: 				       {'js_ready'  => 1,
                   1244: 					'only_body' => 1,
                   1245: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1246:     my $end_page_highlight_central = 
1.350     albertel 1247: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1248: 
1.219     www      1249:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1250:     $docopen=~s/^document\.//;
1.71      ng       1251:     $request->print(<<SUBJAVASCRIPT);
                   1252: <script type="text/javascript" language="javascript">
1.45      ng       1253: 
1.44      ng       1254: //===================== Show list of keywords ====================
1.122     ng       1255:   function keywords(formname) {
                   1256:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1257:     if (nret==null) return;
1.122     ng       1258:     formname.keywords.value = nret;
1.44      ng       1259: 
1.122     ng       1260:     if (formname.keywords.value != "") {
1.128     ng       1261: 	formname.refresh.value = "on";
1.122     ng       1262: 	formname.submit();
1.44      ng       1263:     }
                   1264:     return;
                   1265:   }
                   1266: 
                   1267: //===================== Script to view submitted by ==================
                   1268:   function viewSubmitter(submitter) {
                   1269:     document.SCORE.refresh.value = "on";
                   1270:     document.SCORE.NCT.value = "1";
                   1271:     document.SCORE.unamedom0.value = submitter;
                   1272:     document.SCORE.submit();
                   1273:     return;
                   1274:   }
                   1275: 
                   1276: //===================== Script to add keyword(s) ==================
                   1277:   function getSel() {
                   1278:     if (document.getSelection) txt = document.getSelection();
                   1279:     else if (document.selection) txt = document.selection.createRange().text;
                   1280:     else return;
                   1281:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1282:     if (cleantxt=="") {
1.46      ng       1283: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1284: 	return;
                   1285:     }
                   1286:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1287:     if (nret==null) return;
1.127     ng       1288:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1289:     if (document.SCORE.keywords.value != "") {
1.127     ng       1290: 	document.SCORE.refresh.value = "on";
1.44      ng       1291: 	document.SCORE.submit();
                   1292:     }
                   1293:     return;
                   1294:   }
                   1295: 
                   1296: //====================== Script for composing message ==============
1.80      ng       1297:    // preload images
                   1298:    img1 = new Image();
                   1299:    img1.src = "$iconpath/mailbkgrd.gif";
                   1300:    img2 = new Image();
                   1301:    img2.src = "$iconpath/mailto.gif";
                   1302: 
1.44      ng       1303:   function msgCenter(msgform,usrctr,fullname) {
                   1304:     var Nmsg  = msgform.savemsgN.value;
                   1305:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1306:     var subject = msgform.msgsub.value;
1.127     ng       1307:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1308:     re = /msgsub/;
                   1309:     var shwsel = "";
                   1310:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1311:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1312:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1313:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1314: 	var testmsg = "savemsg"+i+",";
                   1315: 	re = new RegExp(testmsg,"g");
1.44      ng       1316: 	shwsel = "";
                   1317: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1318: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1319: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1320: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1321: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1322:     }
1.125     ng       1323:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1324:     shwsel = "";
                   1325:     re = /newmsg/;
                   1326:     if (re.test(msgchk)) { shwsel = "checked" }
                   1327:     newMsg(newmsg,shwsel);
                   1328:     msgTail(); 
                   1329:     return;
                   1330:   }
                   1331: 
1.123     ng       1332:   function checkEntities(strx) {
                   1333:     if (strx.length == 0) return strx;
                   1334:     var orgStr = ["&", "<", ">", '"']; 
                   1335:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1336:     var counter = 0;
                   1337:     while (counter < 4) {
                   1338: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1339: 	counter++;
                   1340:     }
                   1341:     return strx;
                   1342:   }
                   1343: 
                   1344:   function strReplace(strx, orgStr, newStr) {
                   1345:     return strx.split(orgStr).join(newStr);
                   1346:   }
                   1347: 
1.44      ng       1348:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1349:     var height = 70*Nmsg+250;
1.44      ng       1350:     var scrollbar = "no";
                   1351:     if (height > 600) {
                   1352: 	height = 600;
                   1353: 	scrollbar = "yes";
                   1354:     }
1.118     ng       1355:     var xpos = (screen.width-600)/2;
                   1356:     xpos = (xpos < 0) ? '0' : xpos;
                   1357:     var ypos = (screen.height-height)/2-30;
                   1358:     ypos = (ypos < 0) ? '0' : ypos;
                   1359: 
1.206     albertel 1360:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1361:     pWin.focus();
                   1362:     pDoc = pWin.document;
1.219     www      1363:     pDoc.$docopen;
1.351     albertel 1364:     pDoc.write('$start_page_msg_central');
1.76      ng       1365: 
                   1366:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1367:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.398     albertel 1368:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
1.76      ng       1369: 
                   1370:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1371:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1372:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1.44      ng       1373: }
                   1374:     function displaySubject(msg,shwsel) {
1.76      ng       1375:     pDoc = pWin.document;
                   1376:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1377:     pDoc.write("<td>Subject</td>");
                   1378:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1379:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1.44      ng       1380: }
                   1381: 
1.72      ng       1382:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1383:     pDoc = pWin.document;
                   1384:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1385:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
                   1386:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1387:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1.44      ng       1388: }
                   1389: 
                   1390:   function newMsg(newmsg,shwsel) {
1.76      ng       1391:     pDoc = pWin.document;
                   1392:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1393:     pDoc.write("<td align=\\"center\\">New</td>");
                   1394:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1395:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1.44      ng       1396: }
                   1397: 
                   1398:   function msgTail() {
1.76      ng       1399:     pDoc = pWin.document;
                   1400:     pDoc.write("</table>");
                   1401:     pDoc.write("</td></tr></table>&nbsp;");
                   1402:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1403:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1404:     pDoc.write("</form>");
1.351     albertel 1405:     pDoc.write('$end_page_msg_central');
1.128     ng       1406:     pDoc.close();
1.44      ng       1407: }
                   1408: 
                   1409: //====================== Script for keyword highlight options ==============
                   1410:   function kwhighlight() {
                   1411:     var kwclr    = document.SCORE.kwclr.value;
                   1412:     var kwsize   = document.SCORE.kwsize.value;
                   1413:     var kwstyle  = document.SCORE.kwstyle.value;
                   1414:     var redsel = "";
                   1415:     var grnsel = "";
                   1416:     var blusel = "";
                   1417:     if (kwclr=="red")   {var redsel="checked"};
                   1418:     if (kwclr=="green") {var grnsel="checked"};
                   1419:     if (kwclr=="blue")  {var blusel="checked"};
                   1420:     var sznsel = "";
                   1421:     var sz1sel = "";
                   1422:     var sz2sel = "";
                   1423:     if (kwsize=="0")  {var sznsel="checked"};
                   1424:     if (kwsize=="+1") {var sz1sel="checked"};
                   1425:     if (kwsize=="+2") {var sz2sel="checked"};
                   1426:     var synsel = "";
                   1427:     var syisel = "";
                   1428:     var sybsel = "";
                   1429:     if (kwstyle=="")    {var synsel="checked"};
                   1430:     if (kwstyle=="<i>") {var syisel="checked"};
                   1431:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1432:     highlightCentral();
                   1433:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1434:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1435:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1436:     highlightend();
                   1437:     return;
                   1438:   }
                   1439: 
                   1440:   function highlightCentral() {
1.76      ng       1441: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1442:     var xpos = (screen.width-400)/2;
                   1443:     xpos = (xpos < 0) ? '0' : xpos;
                   1444:     var ypos = (screen.height-330)/2-30;
                   1445:     ypos = (ypos < 0) ? '0' : ypos;
                   1446: 
1.206     albertel 1447:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1448:     hwdWin.focus();
                   1449:     var hDoc = hwdWin.document;
1.219     www      1450:     hDoc.$docopen;
1.351     albertel 1451:     hDoc.write('$start_page_highlight_central');
1.76      ng       1452:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.398     albertel 1453:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
1.76      ng       1454: 
                   1455:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1456:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1457:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1.44      ng       1458:   }
                   1459: 
                   1460:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1461:     var hDoc = hwdWin.document;
                   1462:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1463:     hDoc.write("<td align=\\"left\\">");
                   1464:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
                   1465:     hDoc.write("<td align=\\"left\\">");
                   1466:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
                   1467:     hDoc.write("<td align=\\"left\\">");
                   1468:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
                   1469:     hDoc.write("</tr>");
1.44      ng       1470:   }
                   1471: 
                   1472:   function highlightend() { 
1.76      ng       1473:     var hDoc = hwdWin.document;
                   1474:     hDoc.write("</table>");
                   1475:     hDoc.write("</td></tr></table>&nbsp;");
                   1476:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1477:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1478:     hDoc.write("</form>");
1.351     albertel 1479:     hDoc.write('$end_page_highlight_central');
1.128     ng       1480:     hDoc.close();
1.44      ng       1481:   }
                   1482: 
                   1483: </script>
                   1484: SUBJAVASCRIPT
                   1485: }
                   1486: 
1.349     albertel 1487: sub get_increment {
1.348     bowersj2 1488:     my $increment = $env{'form.increment'};
                   1489:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1490:         $increment != .1) {
                   1491:         $increment = 1;
                   1492:     }
                   1493:     return $increment;
                   1494: }
                   1495: 
1.71      ng       1496: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1497: sub gradeBox {
1.322     albertel 1498:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1499:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1500: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1501: 	'/check.gif" height="16" border="0" />';
                   1502:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
                   1503:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
1.398     albertel 1504: 		  '<span class="LC_info">problem weight assigned by computer</span>');
1.71      ng       1505:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1506:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1507: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1508:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.324     albertel 1509:     my $display_part=&get_display_part($partid,$symb);
1.270     albertel 1510:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1511: 				       [$partid]);
                   1512:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1513:     if ($last_resets{$partid}) {
                   1514:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1515:     }
1.71      ng       1516:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1517: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1518:     my $ctr = 0;
1.348     bowersj2 1519:     my $thisweight = 0;
1.349     albertel 1520:     my $increment = &get_increment();
1.71      ng       1521:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1522:     while ($thisweight<=$wgt) {
1.381     albertel 1523: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1524: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1525: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1526: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1527: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1528:         $thisweight += $increment;
1.71      ng       1529: 	$ctr++;
                   1530:     }
                   1531:     $result.='</tr></table>';
                   1532:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1533:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1534: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1535: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1536: 	$wgt.')" /></td>'."\n";
                   1537:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1538: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1539: 	' </td><td>'."\n";
                   1540:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1541: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1542:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1543: 	$result.='<option></option>'.
1.401     albertel 1544: 	    '<option selected="selected">excused</option>';
1.71      ng       1545:     } else {
1.401     albertel 1546: 	$result.='<option selected="selected"></option>'.
1.125     ng       1547: 	    '<option>excused</option>';
1.71      ng       1548:     }
1.125     ng       1549:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1550:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1551:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1552: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1553: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1554: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1555:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1556:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1557:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1558:         $aggtries.'" />'."\n";
1.71      ng       1559:     $result.='</td></tr></table>'."\n";
1.323     banghart 1560:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1561:     return $result;
                   1562: }
1.322     albertel 1563: 
                   1564: sub handback_box {
1.323     banghart 1565:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1566:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1567:     my (@respids);
1.375     albertel 1568:      my @part_response_id = &flatten_responseType($responseType);
                   1569:     foreach my $part_response_id (@part_response_id) {
                   1570:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1571:         if ($part eq $partid) {
1.375     albertel 1572:             push(@respids,$resp);
1.323     banghart 1573:         }
                   1574:     }
1.318     banghart 1575:     my $result;
1.323     banghart 1576:     foreach my $respid (@respids) {
1.322     albertel 1577: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1578: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1579: 	next if (!@$files);
                   1580: 	my $file_counter = 1;
1.313     banghart 1581: 	foreach my $file (@$files) {
1.368     banghart 1582: 	    if ($file =~ /\/portfolio\//) {
                   1583:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1584:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1585:     	        $file_disp = "$name.$ext";
                   1586:     	        $file = $file_path.$file_disp;
                   1587:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1588:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1589:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1590:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.369     banghart 1591:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1.368     banghart 1592:     	        $file_counter++;
                   1593: 	    }
1.322     albertel 1594: 	}
1.313     banghart 1595:     }
1.318     banghart 1596:     return $result;    
1.71      ng       1597: }
1.44      ng       1598: 
1.58      albertel 1599: sub show_problem {
1.382     albertel 1600:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1601:     my $rendered;
1.382     albertel 1602:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1603:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1604:     if ($mode eq 'both' or $mode eq 'text') {
                   1605: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1606: 						       $env{'request.course.id'},
                   1607: 						       undef,\%form);
1.144     albertel 1608:     }
1.58      albertel 1609:     if ($removeform) {
                   1610: 	$rendered=~s|<form(.*?)>||g;
                   1611: 	$rendered=~s|</form>||g;
1.374     albertel 1612: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1613:     }
1.144     albertel 1614:     my $companswer;
                   1615:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1616: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1617: 	$companswer=
                   1618: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1619: 						    $env{'request.course.id'},
                   1620: 						    %form);
1.144     albertel 1621:     }
1.58      albertel 1622:     if ($removeform) {
                   1623: 	$companswer=~s|<form(.*?)>||g;
                   1624: 	$companswer=~s|</form>||g;
1.144     albertel 1625: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1626:     }
                   1627:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1628:     $result.='<table border="0" width="100%">';
1.144     albertel 1629:     if ($viewon) {
                   1630: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1631: 	if ($mode eq 'both' or $mode eq 'text') {
                   1632: 	    $result.='View of the problem - ';
                   1633: 	} else {
                   1634: 	    $result.='Correct answer: ';
                   1635: 	}
1.257     albertel 1636: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1637:     }
                   1638:     if ($mode eq 'both') {
                   1639: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1640: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1641:     } elsif ($mode eq 'text') {
                   1642: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1643:     } elsif ($mode eq 'answer') {
                   1644: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1645:     }
1.58      albertel 1646:     $result.='</td></tr></table>';
                   1647:     $result.='</td></tr></table><br />';
1.71      ng       1648:     return $result;
1.58      albertel 1649: }
1.397     albertel 1650: 
1.396     banghart 1651: sub files_exist {
                   1652:     my ($r, $symb) = @_;
                   1653:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1654: 
1.396     banghart 1655:     foreach my $student (@students) {
                   1656:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1657:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1658: 					      $udom,$uname);
1.396     banghart 1659:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1660:         foreach my $submission (@$string) {
                   1661:             my ($partid,$respid) =
                   1662: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1663:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1664: 					   \%record);
                   1665:             return 1 if (@$files);
1.396     banghart 1666:         }
                   1667:     }
1.397     albertel 1668:     return 0;
1.396     banghart 1669: }
1.397     albertel 1670: 
1.394     banghart 1671: sub download_all_link {
                   1672:     my ($r,$symb) = @_;
1.395     albertel 1673:     my $all_students = 
                   1674: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1675: 
                   1676:     my $parts =
                   1677: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1678: 
1.394     banghart 1679:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1680:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1681:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1682:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1683:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1684: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1685:     return
                   1686: }
1.395     albertel 1687: 
1.432     banghart 1688: sub build_section_inputs {
                   1689:     my $section_inputs;
                   1690:     if ($env{'form.section'} eq '') {
                   1691:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1692:     } else {
                   1693:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1694:         foreach my $section (@sections) {
1.432     banghart 1695:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1696:         }
                   1697:     }
                   1698:     return $section_inputs;
                   1699: }
                   1700: 
1.44      ng       1701: # --------------------------- show submissions of a student, option to grade 
                   1702: sub submission {
                   1703:     my ($request,$counter,$total) = @_;
                   1704: 
1.257     albertel 1705:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1706:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1707:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1708:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1709:     my $symb = &get_symb($request); 
                   1710:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1711: 
                   1712:     if (!&canview($usec)) {
1.398     albertel 1713: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1714: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1715: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1716: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1717: 	return;
                   1718:     }
                   1719: 
1.257     albertel 1720:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1721:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1722:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1723:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1724:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1725: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1726: 	'/check.gif" height="16" border="0" />';
1.41      ng       1727: 
1.426     albertel 1728:     my %old_essays;
1.41      ng       1729:     # header info
                   1730:     if ($counter == 0) {
                   1731: 	&sub_page_js($request);
1.257     albertel 1732: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1733: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1734: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1735: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1736: 	    &download_all_link($request, $symb);
                   1737: 	}
1.398     albertel 1738: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
                   1739: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1.118     ng       1740: 
1.257     albertel 1741: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1742: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1743: 		$checkIcon.' symbol.'."\n";
                   1744: 	    $request->print($checkMark);
                   1745: 	}
1.41      ng       1746: 
1.44      ng       1747: 	# option to display problem, only once else it cause problems 
                   1748:         # with the form later since the problem has a form.
1.257     albertel 1749: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1750: 	    my $mode;
1.257     albertel 1751: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1752: 		$mode='both';
1.257     albertel 1753: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1754: 		$mode='text';
1.257     albertel 1755: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1756: 		$mode='answer';
                   1757: 	    }
1.329     albertel 1758: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1759: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1760: 	}
1.441   ! www      1761: 
1.44      ng       1762: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1763:         # if this subroutine has been called once.
1.41      ng       1764: 	my %keyhash = ();
1.257     albertel 1765: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1766: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1767: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1768: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1769: 
1.257     albertel 1770: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1771: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1772: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1773: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1774: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1775: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1776: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1777: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1778: 	}
1.257     albertel 1779: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.303     banghart 1780: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1781: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1782: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
                   1783: 			'<input type="hidden" name="Status"     value="'.$env{'form.Status'}.'" />'."\n".
1.120     ng       1784: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1785: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1786: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1787: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1788: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1789: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1790: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1791: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1792: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1793: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1794: 			&build_section_inputs().
1.326     albertel 1795: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1796: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1797: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1798: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1799: 	if ($env{'form.handgrade'} eq 'yes') {
                   1800: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1801: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1802: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1803: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1804: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1805: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1806: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1807: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1808: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1809: 	    }
1.123     ng       1810: 	}
1.41      ng       1811: 	
                   1812: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1813: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1814: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1815: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1816: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1817: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1818: 		'" />'."\n".
                   1819: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1820: 	    $cts++;
                   1821: 	}
                   1822: 	$request->print($prnmsg);
1.32      ng       1823: 
1.257     albertel 1824: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1825: #
                   1826: # Print out the keyword options line
                   1827: #
1.41      ng       1828: 	    $request->print(<<KEYWORDS);
1.38      ng       1829: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1830: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1831: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1832:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1833: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1834: KEYWORDS
1.88      www      1835: #
                   1836: # Load the other essays for similarity check
                   1837: #
1.324     albertel 1838:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1839: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1840: 	    $apath=&escape($apath);
1.88      www      1841: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1842: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1843:         }
                   1844:     }
1.44      ng       1845: 
1.441   ! www      1846: # This is where output for one specific student would start
        !          1847:     my $bgcolor='#DDEEDD';
        !          1848:     if (int($counter/2) eq $counter) { $bgcolor='#DDDDEE'; }
        !          1849:     $request->print("\n\n".
        !          1850:                     '<p><table border="2"><tr><th bgcolor="'.$bgcolor.'">'.$env{'form.fullname'}.'</th></tr><tr><td bgcolor="'.$bgcolor.'">');
        !          1851: 
1.257     albertel 1852:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 1853: 	my $mode;
1.257     albertel 1854: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1855: 	    $mode='both';
1.257     albertel 1856: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1857: 	    $mode='text';
1.257     albertel 1858: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1859: 	    $mode='answer';
                   1860: 	}
1.329     albertel 1861: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1862: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1863:     }
1.144     albertel 1864: 
1.257     albertel 1865:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1866:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1867: 
1.44      ng       1868:     # Display student info
1.41      ng       1869:     $request->print(($counter == 0 ? '' : '<br />'));
1.326     albertel 1870:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
                   1871: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1.44      ng       1872: 
1.257     albertel 1873:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1.45      ng       1874:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1875: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1876: 
1.118     ng       1877:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.45      ng       1878:     my @col_fullnames;
1.56      matthew  1879:     my ($classlist,$fullname);
1.257     albertel 1880:     if ($env{'form.handgrade'} eq 'yes') {
1.80      ng       1881: 	($classlist,undef,$fullname) = &getclasslist('all','0');
1.41      ng       1882: 	for (keys (%$handgrade)) {
1.44      ng       1883: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1.57      matthew  1884: 					    '.maxcollaborators',
                   1885:                                             $symb,$udom,$uname);
                   1886: 	    next if ($ncol <= 0);
                   1887:             s/\_/\./g;
                   1888:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
1.86      ng       1889:             my @goodcollaborators = ();
                   1890:             my @badcollaborators  = ();
                   1891: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
                   1892: 		$_ =~ s/[\$\^\(\)]//g;
                   1893: 		next if ($_ eq '');
1.80      ng       1894: 		my ($co_name,$co_dom) = split /\@|:/,$_;
1.86      ng       1895: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1.80      ng       1896: 		next if ($co_name eq $uname && $co_dom eq $udom);
1.86      ng       1897: 		# Doing this grep allows 'fuzzy' specification
                   1898: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
                   1899: 		if (! scalar(@Matches)) {
                   1900: 		    push @badcollaborators,$_;
                   1901: 		} else {
                   1902: 		    push @goodcollaborators, @Matches;
                   1903: 		}
1.80      ng       1904: 	    }
1.86      ng       1905:             if (scalar(@goodcollaborators) != 0) {
1.57      matthew  1906:                 $result.='<b>Collaborators: </b>';
1.86      ng       1907:                 foreach (@goodcollaborators) {
                   1908: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
                   1909: 		    push @col_fullnames, $givenn.' '.$lastname;
                   1910: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
                   1911: 		}
1.57      matthew  1912:                 $result.='<br />'."\n";
1.150     albertel 1913: 		my ($part)=split(/\./,$_);
1.86      ng       1914: 		$result.='<input type="hidden" name="collaborator'.$counter.
1.150     albertel 1915: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
                   1916: 		    "\n";
1.86      ng       1917: 	    }
                   1918: 	    if (scalar(@badcollaborators) > 0) {
                   1919: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1920: 		$result.='This student has submitted ';
                   1921: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
                   1922: 		$result .= ': '.join(', ',@badcollaborators);
                   1923: 		$result .= '</td></tr></table>';
                   1924: 	    }         
                   1925: 	    if (scalar(@badcollaborators > $ncol)) {
                   1926: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1927: 		$result .= 'This student has submitted too many '.
                   1928: 		    'collaborators.  Maximum is '.$ncol.'.';
                   1929: 		$result .= '</td></tr></table>';
                   1930: 	    }
1.41      ng       1931: 	}
                   1932:     }
1.44      ng       1933:     $request->print($result."\n");
1.33      ng       1934: 
1.44      ng       1935:     # print student answer/submission
                   1936:     # Options are (1) Handgaded submission only
                   1937:     #             (2) Last submission, includes submission that is not handgraded 
                   1938:     #                  (for multi-response type part)
                   1939:     #             (3) Last submission plus the parts info
                   1940:     #             (4) The whole record for this student
1.257     albertel 1941:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 1942: 	my ($string,$timestamp)= &get_last_submission(\%record);
                   1943: 	my $lastsubonly=''.
                   1944: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
                   1945: 	     $$timestamp)."</td></tr>\n";
                   1946: 	if ($$timestamp eq '') {
                   1947: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
                   1948: 	} else {
                   1949: 	    my %seenparts;
1.375     albertel 1950: 	    my @part_response_id = &flatten_responseType($responseType);
                   1951: 	    foreach my $part (@part_response_id) {
1.393     albertel 1952: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   1953: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   1954: 
1.375     albertel 1955: 		my ($partid,$respid) = @{ $part };
1.324     albertel 1956: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 1957: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 1958: 		    if (exists($seenparts{$partid})) { next; }
                   1959: 		    $seenparts{$partid}=1;
1.207     albertel 1960: 		    my $submitby='<b>Part:</b> '.$display_part.
                   1961: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 1962: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 1963: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 1964: 			'\');" target="_self">'.
1.257     albertel 1965: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 1966: 		    $request->print($submitby);
                   1967: 		    next;
                   1968: 		}
                   1969: 		my $responsetype = $responseType->{$partid}->{$respid};
                   1970: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.207     albertel 1971: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1.398     albertel 1972: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   1973: 			' )</span>&nbsp; &nbsp;'.
                   1974: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1.151     albertel 1975: 		    next;
                   1976: 		}
                   1977: 		foreach (@$string) {
                   1978: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1.375     albertel 1979: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.151     albertel 1980: 		    my ($ressub,$subval) = split(/:/,$_,2);
                   1981: 		    # Similarity check
                   1982: 		    my $similar='';
1.257     albertel 1983: 		    if($env{'form.checkPlag'}){
1.151     albertel 1984: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 1985: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 1986: 			if ($osim) {
                   1987: 			    $osim=int($osim*100.0);
1.426     albertel 1988: 			    my %old_course_desc = 
                   1989: 				&Apache::lonnet::coursedescription($ocrsid,
                   1990: 								   {'one_time' => 1});
                   1991: 
                   1992: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 1993: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 1994: 				    $osim,
                   1995: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 1996: 				    $oname,$odom,
1.426     albertel 1997: 				    $old_course_desc{'description'},
1.427     albertel 1998: 				    $old_course_desc{'num'},
1.426     albertel 1999: 				    $old_course_desc{'domain'}).
1.398     albertel 2000: 				'</span></h3><blockquote><i>'.
1.151     albertel 2001: 				&keywords_highlight($oessay).
                   2002: 				'</i></blockquote><hr />';
                   2003: 			}
1.150     albertel 2004: 		    }
1.151     albertel 2005: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2006: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2007: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2008: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2009: 			my $display_part=&get_display_part($partid,$symb);
1.403     albertel 2010: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   2011: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2012: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2013: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2014: 			if (@$files) {
1.398     albertel 2015: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1.303     banghart 2016: 			    my $file_counter = 0;
1.313     banghart 2017: 			    foreach my $file (@$files) {
1.303     banghart 2018: 			        $file_counter ++;
1.232     albertel 2019: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2020: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2021: 			    }
1.236     albertel 2022: 			    $lastsubonly.='<br />';
1.41      ng       2023: 			}
1.151     albertel 2024: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   2025: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2026: 					 $respid,\%record,$order);
                   2027: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       2028: 		    }
                   2029: 		}
                   2030: 	    }
1.151     albertel 2031: 	}
                   2032: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   2033: 	$request->print($lastsubonly);
1.257     albertel 2034:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2035: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2036: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2037:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2038: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2039: 								 $env{'request.course.id'},
1.44      ng       2040: 								 $last,'.submission',
                   2041: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2042:     }
1.120     ng       2043: 
1.121     ng       2044:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2045: 	.$udom.'" />'."\n");
1.41      ng       2046:     
1.44      ng       2047:     # return if view submission with no grading option
1.257     albertel 2048:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2049: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2050: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2051: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 2052: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 2053: 	if (($env{'form.command'} eq 'submission') || 
                   2054: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2055: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2056: 	}
1.180     albertel 2057: 	$request->print($toGrade);
1.41      ng       2058: 	return;
1.180     albertel 2059:     } else {
                   2060: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       2061:     }
1.33      ng       2062: 
1.121     ng       2063:     # essay grading message center
1.257     albertel 2064:     if ($env{'form.handgrade'} eq 'yes') {
                   2065: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2066: 	my $msgfor = $givenn.' '.$lastname;
                   2067: 	if (scalar(@col_fullnames) > 0) {
                   2068: 	    my $lastone = pop @col_fullnames;
                   2069: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   2070: 	}
                   2071: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       2072: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2073: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2074: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2075: 	    ',\''.$msgfor.'\');" target="_self">'.
1.350     albertel 2076: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
                   2077: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2078: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2079: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2080: 	    '<br />&nbsp;('.
                   2081: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       2082: 	$request->print($result);
1.118     ng       2083:     }
1.300     albertel 2084:     if ($perm{'vgr'}) {
1.297     www      2085: 	$request->print('<br />'.
1.300     albertel 2086: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2087: 						   $uname,$udom,'check'));
1.297     www      2088:     }
1.300     albertel 2089:     if ($perm{'opa'}) {
1.297     www      2090: 	$request->print('<br />'.
1.300     albertel 2091: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2092: 					 $uname,$udom,$symb,'check'));
1.297     www      2093:     }
1.41      ng       2094: 
                   2095:     my %seen = ();
                   2096:     my @partlist;
1.129     ng       2097:     my @gradePartRespid;
1.375     albertel 2098:     my @part_response_id = &flatten_responseType($responseType);
                   2099:     foreach my $part_response_id (@part_response_id) {
                   2100:     	my ($partid,$respid) = @{ $part_response_id };
                   2101: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2102: 	next if ($seen{$partid} > 0);
1.41      ng       2103: 	$seen{$partid}++;
1.393     albertel 2104: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2105: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2106: 	push @partlist,$partid;
1.129     ng       2107: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2108: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2109:     }
1.45      ng       2110:     $result='<input type="hidden" name="partlist'.$counter.
                   2111: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2112:     $result.='<input type="hidden" name="gradePartRespid'.
                   2113: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2114:     my $ctr = 0;
                   2115:     while ($ctr < scalar(@partlist)) {
                   2116: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2117: 	    $partlist[$ctr].'" />'."\n";
                   2118: 	$ctr++;
                   2119:     }
                   2120:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       2121: 
1.441   ! www      2122: # Done with printing info for one student
        !          2123: 
        !          2124:     $request->print('</td></tr></table></p>');
        !          2125: 
        !          2126: 
1.41      ng       2127:     # print end of form
                   2128:     if ($counter == $total) {
1.297     www      2129: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2130: 	$endform.='<input type="button" value="Save & Next" '.
                   2131: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2132: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2133: 	my $ntstu ='<select name="NTSTU">'.
                   2134: 	    '<option>1</option><option>2</option>'.
                   2135: 	    '<option>3</option><option>5</option>'.
                   2136: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2137: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2138: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.119     ng       2139: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2140: 	$endform.='<input type="button" value="Previous" '.
1.417     albertel 2141: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.126     ng       2142: 	    '<input type="button" value="Next" '.
1.417     albertel 2143: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.126     ng       2144: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2145:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2146:             "' name='increment' />";
1.45      ng       2147: 	$endform.='</td><tr></table></form>';
1.324     albertel 2148: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2149: 	$request->print($endform);
                   2150:     }
                   2151:     return '';
1.38      ng       2152: }
                   2153: 
1.44      ng       2154: #--- Retrieve the last submission for all the parts
1.38      ng       2155: sub get_last_submission {
1.119     ng       2156:     my ($returnhash)=@_;
1.46      ng       2157:     my (@string,$timestamp);
1.119     ng       2158:     if ($$returnhash{'version'}) {
1.46      ng       2159: 	my %lasthash=();
                   2160: 	my ($version);
1.119     ng       2161: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2162: 	    foreach my $key (sort(split(/\:/,
                   2163: 					$$returnhash{$version.':keys'}))) {
                   2164: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2165: 		$timestamp = 
                   2166: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2167: 	    }
                   2168: 	}
1.397     albertel 2169: 	foreach my $key (keys(%lasthash)) {
                   2170: 	    next if ($key !~ /\.submission$/);
                   2171: 
                   2172: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2173: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2174: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2175: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2176: 	}
                   2177:     }
1.397     albertel 2178:     if (!@string) {
                   2179: 	$string[0] =
1.398     albertel 2180: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2181:     }
                   2182:     return (\@string,\$timestamp);
1.38      ng       2183: }
1.35      ng       2184: 
1.44      ng       2185: #--- High light keywords, with style choosen by user.
1.38      ng       2186: sub keywords_highlight {
1.44      ng       2187:     my $string    = shift;
1.257     albertel 2188:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2189:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2190:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2191:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2192:     foreach my $keyword (@keylist) {
                   2193: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2194:     }
                   2195:     return $string;
1.38      ng       2196: }
1.36      ng       2197: 
1.44      ng       2198: #--- Called from submission routine
1.38      ng       2199: sub processHandGrade {
1.41      ng       2200:     my ($request) = shift;
1.324     albertel 2201:     my $symb   = &get_symb($request);
                   2202:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2203:     my $button = $env{'form.gradeOpt'};
                   2204:     my $ngrade = $env{'form.NCT'};
                   2205:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2206:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2207:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2208: 
1.44      ng       2209:     if ($button eq 'Save & Next') {
                   2210: 	my $ctr = 0;
                   2211: 	while ($ctr < $ngrade) {
1.257     albertel 2212: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2213: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2214: 	    if ($errorflag eq 'no_score') {
                   2215: 		$ctr++;
                   2216: 		next;
                   2217: 	    }
1.104     albertel 2218: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2219: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2220: 		$ctr++;
                   2221: 		next;
                   2222: 	    }
1.257     albertel 2223: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2224: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2225: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2226:             my ($feedurl,$showsymb) =
                   2227: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2228: 	    my $messagetail;
1.62      albertel 2229: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2230: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2231: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2232: 		$subject.=' ['.$restitle.']';
1.44      ng       2233: 		my (@msgnum) = split(/,/,$includemsg);
                   2234: 		foreach (@msgnum) {
1.257     albertel 2235: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2236: 		}
1.80      ng       2237: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2238: 		if ($env{'form.withgrades'.$ctr}) {
                   2239: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2240: 		    $messagetail = " for <a href=\"".
1.418     albertel 2241: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2242: 		}
                   2243: 		$msgstatus = 
                   2244:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2245: 						     $message.$messagetail,
1.418     albertel 2246:                                                      undef,$feedurl,undef,
1.386     raeburn  2247:                                                      undef,undef,$showsymb,
                   2248:                                                      $restitle);
                   2249: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2250: 				$msgstatus);
1.44      ng       2251: 	    }
1.257     albertel 2252: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2253: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2254: 		foreach my $collabstr (@collabstrs) {
                   2255: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2256: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2257: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2258: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2259: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2260: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2261: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2262: 			    next;
1.418     albertel 2263: 			} elsif ($message ne '') {
                   2264: 			    my ($baseurl,$showsymb) = 
                   2265: 				&get_feedurl_and_symb($symb,$collaborator,
                   2266: 						      $udom);
                   2267: 			    if ($env{'form.withgrades'.$ctr}) {
                   2268: 				$messagetail = " for <a href=\"".
1.386     raeburn  2269:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2270: 			    }
1.418     albertel 2271: 			    $msgstatus = 
                   2272: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2273: 			}
1.44      ng       2274: 		    }
                   2275: 		}
                   2276: 	    }
                   2277: 	    $ctr++;
                   2278: 	}
                   2279:     }
                   2280: 
1.257     albertel 2281:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2282: 	# Keywords sorted in alphabatical order
1.257     albertel 2283: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2284: 	my %keyhash = ();
1.257     albertel 2285: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2286: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2287: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2288: 	$env{'form.keywords'} = join(' ',@keywords);
                   2289: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2290: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2291: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2292: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2293: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2294: 
                   2295: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2296: 	# New messages are saved in env for the next student.
1.119     ng       2297: 	# All messages are saved in nohist_handgrade.db
                   2298: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2299: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2300: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2301: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2302: 		$idx++;
                   2303: 	    }
                   2304: 	    $ctr++;
1.41      ng       2305: 	}
1.119     ng       2306: 	$ctr = 0;
                   2307: 	while ($ctr < $ngrade) {
1.257     albertel 2308: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2309: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2310: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2311: 		$idx++;
                   2312: 	    }
                   2313: 	    $ctr++;
1.41      ng       2314: 	}
1.257     albertel 2315: 	$env{'form.savemsgN'} = --$idx;
                   2316: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2317: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2318: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2319:     }
1.44      ng       2320:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2321:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2322:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2323: 	my ($ctr,$total) = (0,0);
                   2324: 	while ($ctr < $ngrade) {
1.257     albertel 2325: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2326: 	    $ctr++;
                   2327: 	}
1.257     albertel 2328: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2329: 	$ctr = 0;
                   2330: 	while ($ctr < $total) {
1.257     albertel 2331: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2332: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2333: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2334: 	    &submission($request,$ctr,$total-1);
1.41      ng       2335: 	    $ctr++;
                   2336: 	}
                   2337: 	return '';
                   2338:     }
1.36      ng       2339: 
1.121     ng       2340: # Go directly to grade student - from submission or link from chart page
1.120     ng       2341:     if ($button eq 'Grade Student') {
1.324     albertel 2342: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2343: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2344: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2345: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2346: 	&submission($request,0,0);
                   2347: 	return '';
                   2348:     }
                   2349: 
1.44      ng       2350:     # Get the next/previous one or group of students
1.257     albertel 2351:     my $firststu = $env{'form.unamedom0'};
                   2352:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2353:     my $ctr = 2;
1.41      ng       2354:     while ($laststu eq '') {
1.257     albertel 2355: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2356: 	$ctr++;
                   2357: 	$laststu = $firststu if ($ctr > $ngrade);
                   2358:     }
1.44      ng       2359: 
1.41      ng       2360:     my (@parsedlist,@nextlist);
                   2361:     my ($nextflg) = 0;
1.294     albertel 2362:     foreach (sort 
                   2363: 	     {
                   2364: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2365: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2366: 		 }
                   2367: 		 return $a cmp $b;
                   2368: 	     } (keys(%$fullname))) {
1.41      ng       2369: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2370: 	    push @parsedlist,$_;
                   2371: 	}
                   2372: 	$nextflg = 1 if ($_ eq $laststu);
                   2373: 	if ($button eq 'Previous') {
                   2374: 	    last if ($_ eq $firststu);
                   2375: 	    push @parsedlist,$_;
                   2376: 	}
                   2377:     }
                   2378:     $ctr = 0;
                   2379:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2380:     my ($partlist) = &response_type($symb);
1.41      ng       2381:     foreach my $student (@parsedlist) {
1.257     albertel 2382: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2383: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2384: 	
                   2385: 	if ($submitonly eq 'queued') {
                   2386: 	    my %queue_status = 
                   2387: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2388: 							$udom,$uname);
                   2389: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2390: 	}
                   2391: 
1.156     albertel 2392: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2393: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2394: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2395: 	    my $submitted = 0;
1.248     albertel 2396: 	    my $ungraded = 0;
                   2397: 	    my $incorrect = 0;
1.145     albertel 2398: 	    foreach (keys(%status)) {
                   2399: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2400: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2401: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2402: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2403: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2404: 		    $submitted = 0;
                   2405: 		}
1.41      ng       2406: 	    }
1.156     albertel 2407: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2408: 				     $submitonly eq 'incorrect' ||
                   2409: 				     $submitonly eq 'graded'));
1.248     albertel 2410: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2411: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2412: 	}
                   2413: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2414: 	last if ($ctr == $ntstu);
1.41      ng       2415: 	$ctr++;
                   2416:     }
1.36      ng       2417: 
1.41      ng       2418:     $ctr = 0;
                   2419:     my $total = scalar(@nextlist)-1;
1.39      ng       2420: 
1.41      ng       2421:     foreach (sort @nextlist) {
                   2422: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2423: 	$env{'form.student'}  = $uname;
                   2424: 	$env{'form.userdom'}  = $udom;
                   2425: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2426: 	&submission($request,$ctr,$total);
                   2427: 	$ctr++;
                   2428:     }
                   2429:     if ($total < 0) {
1.398     albertel 2430: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
1.41      ng       2431: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2432: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2433: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2434: 	$request->print($the_end);
                   2435:     }
                   2436:     return '';
1.38      ng       2437: }
1.36      ng       2438: 
1.44      ng       2439: #---- Save the score and award for each student, if changed
1.38      ng       2440: sub saveHandGrade {
1.324     albertel 2441:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2442:     my @version_parts;
1.104     albertel 2443:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2444: 					   $env{'request.course.id'});
1.104     albertel 2445:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2446:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2447:     my @parts_graded;
1.77      ng       2448:     my %newrecord  = ();
                   2449:     my ($pts,$wgt) = ('','');
1.269     raeburn  2450:     my %aggregate = ();
                   2451:     my $aggregateflag = 0;
1.301     albertel 2452:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2453:     foreach my $new_part (@parts) {
1.337     banghart 2454: 	#collaborator ($submi may vary for different parts
1.259     banghart 2455: 	if ($submitter && $new_part ne $part) { next; }
                   2456: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2457: 	if ($dropMenu eq 'excused') {
1.259     banghart 2458: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2459: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2460: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2461: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2462: 		}
1.364     banghart 2463: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2464: 	    }
1.125     ng       2465: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2466: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2467: 	    foreach my $key (keys (%record)) {
1.259     banghart 2468: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2469: 	    }
1.259     banghart 2470: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2471: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2472:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2473: 
                   2474:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2475: 					       [$new_part]);
                   2476:             my $aggtries =$totaltries;
1.269     raeburn  2477:             if ($last_resets{$new_part}) {
1.270     albertel 2478:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2479: 					   $new_part);
1.269     raeburn  2480:             }
1.270     albertel 2481: 
                   2482:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2483:             if ($aggtries > 0) {
1.327     albertel 2484:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2485:                 $aggregateflag = 1;
                   2486:             }
1.125     ng       2487: 	} elsif ($dropMenu eq '') {
1.259     banghart 2488: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2489: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2490: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2491: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2492: 		next;
                   2493: 	    }
1.259     banghart 2494: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2495: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2496: 	    my $partial= $pts/$wgt;
1.259     banghart 2497: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2498: 		#do not update score for part if not changed.
1.346     banghart 2499:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2500: 		next;
1.251     banghart 2501: 	    } else {
1.259     banghart 2502: 	        push @parts_graded, $new_part;
1.153     albertel 2503: 	    }
1.259     banghart 2504: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2505: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2506: 	    }
1.259     banghart 2507: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2508: 	    if ($partial == 0) {
1.153     albertel 2509: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2510: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2511: 		}
1.41      ng       2512: 	    } else {
1.153     albertel 2513: 		if ($record{$reckey} ne 'correct_by_override') {
                   2514: 		    $newrecord{$reckey} = 'correct_by_override';
                   2515: 		}
                   2516: 	    }	    
                   2517: 	    if ($submitter && 
1.259     banghart 2518: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2519: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2520: 	    }
1.259     banghart 2521: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2522: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2523: 	}
1.259     banghart 2524: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2525: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2526: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2527: 	        $dropMenu eq 'reset status')
                   2528: 	   {
1.342     banghart 2529: 	    push (@version_parts,$new_part);
1.259     banghart 2530: 	}
1.41      ng       2531:     }
1.301     albertel 2532:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2533:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2534: 
1.344     albertel 2535:     if (%newrecord) {
                   2536:         if (@version_parts) {
1.364     banghart 2537:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2538:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2539: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2540: 	    foreach my $new_part (@version_parts) {
                   2541: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2542: 				$new_part,\%newrecord);
                   2543: 	    }
1.259     banghart 2544:         }
1.44      ng       2545: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2546: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2547: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2548: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2549:     }
1.269     raeburn  2550:     if ($aggregateflag) {
                   2551:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2552: 			      $cdom,$cnum);
1.269     raeburn  2553:     }
1.301     albertel 2554:     return ('',$pts,$wgt);
1.36      ng       2555: }
1.322     albertel 2556: 
1.380     albertel 2557: sub check_and_remove_from_queue {
                   2558:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2559:     my @ungraded_parts;
                   2560:     foreach my $part (@{$parts}) {
                   2561: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2562: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2563: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2564: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2565: 		) {
                   2566: 	    push(@ungraded_parts, $part);
                   2567: 	}
                   2568:     }
                   2569:     if ( !@ungraded_parts ) {
                   2570: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2571: 					       $cnum,$domain,$stuname);
                   2572:     }
                   2573: }
                   2574: 
1.337     banghart 2575: sub handback_files {
                   2576:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2577:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2578:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2579: 
                   2580:     my @part_response_id = &flatten_responseType($responseType);
                   2581:     foreach my $part_response_id (@part_response_id) {
                   2582:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2583: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2584:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2585:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2586:                 my $file_counter = 1;
1.367     albertel 2587: 		my $file_msg;
1.337     banghart 2588:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2589:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2590:                     my ($directory,$answer_file) = 
                   2591:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2592:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2593: 		        &file_name_version_ext($answer_file);
1.355     banghart 2594: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2595: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2596: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2597:                     # fix file name
                   2598:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2599:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2600:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2601:             	                                $save_file_name);
1.337     banghart 2602:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2603:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2604:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2605:                     } else {
1.360     banghart 2606:                         # mark the file as read only
                   2607:                         my @files = ($save_file_name);
1.372     albertel 2608:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2609:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2610: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2611: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2612: 			}
                   2613:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2614: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2615: 
1.337     banghart 2616:                     }
                   2617:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2618:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2619:                     $file_counter++;
                   2620:                 }
1.367     albertel 2621: 		my $subject = "File Handed Back by Instructor ";
                   2622: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2623: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2624: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2625: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2626: 		my ($feedurl,$showsymb) = 
                   2627: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2628:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2629: 		my $msgstatus = 
                   2630:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2631: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2632:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2633:             }
                   2634:         }
1.338     banghart 2635:     return;
1.337     banghart 2636: }
                   2637: 
1.418     albertel 2638: sub get_feedurl_and_symb {
                   2639:     my ($symb,$uname,$udom) = @_;
                   2640:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2641:     $url = &Apache::lonnet::clutter($url);
                   2642:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2643: 					$symb,$udom,$uname);
                   2644:     if ($encrypturl =~ /^yes$/i) {
                   2645: 	&Apache::lonenc::encrypted(\$url,1);
                   2646: 	&Apache::lonenc::encrypted(\$symb,1);
                   2647:     }
                   2648:     return ($url,$symb);
                   2649: }
                   2650: 
1.313     banghart 2651: sub get_submitted_files {
                   2652:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2653:     my @files;
                   2654:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2655:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2656:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2657:     	    push(@files,$file_url.$file);
                   2658:         }
                   2659:     }
                   2660:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2661:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2662:     }
                   2663:     return (\@files);
                   2664: }
1.322     albertel 2665: 
1.269     raeburn  2666: # ----------- Provides number of tries since last reset.
                   2667: sub get_num_tries {
                   2668:     my ($record,$last_reset,$part) = @_;
                   2669:     my $timestamp = '';
                   2670:     my $num_tries = 0;
                   2671:     if ($$record{'version'}) {
                   2672:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2673:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2674:                 $timestamp = $$record{$version.':timestamp'};
                   2675:                 if ($timestamp > $last_reset) {
                   2676:                     $num_tries ++;
                   2677:                 } else {
                   2678:                     last;
                   2679:                 }
                   2680:             }
                   2681:         }
                   2682:     }
                   2683:     return $num_tries;
                   2684: }
                   2685: 
                   2686: # ----------- Determine decrements required in aggregate totals 
                   2687: sub decrement_aggs {
                   2688:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2689:     my %decrement = (
                   2690:                         attempts => 0,
                   2691:                         users => 0,
                   2692:                         correct => 0
                   2693:                     );
                   2694:     $decrement{'attempts'} = $aggtries;
                   2695:     if ($solvedstatus =~ /^correct/) {
                   2696:         $decrement{'correct'} = 1;
                   2697:     }
                   2698:     if ($aggtries == $totaltries) {
                   2699:         $decrement{'users'} = 1;
                   2700:     }
                   2701:     foreach my $type (keys (%decrement)) {
                   2702:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2703:     }
                   2704:     return;
                   2705: }
                   2706: 
                   2707: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2708: sub get_last_resets {
1.270     albertel 2709:     my ($symb,$courseid,$partids) =@_;
                   2710:     my %last_resets;
1.269     raeburn  2711:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2712:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2713:     my @keys;
                   2714:     foreach my $part (@{$partids}) {
                   2715: 	push(@keys,"$symb\0$part\0resettime");
                   2716:     }
                   2717:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2718: 				     $cdom,$cname);
                   2719:     foreach my $part (@{$partids}) {
                   2720: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2721:     }
1.270     albertel 2722:     return %last_resets;
1.269     raeburn  2723: }
                   2724: 
1.251     banghart 2725: # ----------- Handles creating versions for portfolio files as answers
                   2726: sub version_portfiles {
1.343     banghart 2727:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2728:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2729:     my @returned_keys;
1.255     banghart 2730:     my $parts = join('|', @$parts_graded);
1.359     www      2731:     my $portfolio_root = &propath($domain,$stu_name).
                   2732: 	'/userfiles/portfolio';
1.277     albertel 2733:     foreach my $key (keys(%$record)) {
1.259     banghart 2734:         my $new_portfiles;
1.263     banghart 2735:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2736:             my @versioned_portfiles;
1.367     albertel 2737:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2738:             foreach my $file (@portfiles) {
1.306     banghart 2739:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2740:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2741: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2742: 		    &file_name_version_ext($answer_file);
1.306     banghart 2743:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2744:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2745:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2746:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2747:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2748:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2749:                         [$directory.$new_answer],
1.306     banghart 2750:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2751:                 }
1.252     banghart 2752:             }
1.343     banghart 2753:             $$record{$key} = join(',',@versioned_portfiles);
                   2754:             push(@returned_keys,$key);
1.251     banghart 2755:         }
                   2756:     } 
1.343     banghart 2757:     return (@returned_keys);   
1.305     banghart 2758: }
                   2759: 
1.307     banghart 2760: sub get_next_version {
1.341     banghart 2761:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2762:     my $version;
                   2763:     foreach my $row (@$dir_list) {
                   2764:         my ($file) = split(/\&/,$row,2);
                   2765:         my ($file_name,$file_version,$file_ext) =
                   2766: 	    &file_name_version_ext($file);
                   2767:         if (($file_name eq $answer_name) && 
                   2768: 	    ($file_ext eq $answer_ext)) {
                   2769:                 # gets here if filename and extension match, regardless of version
                   2770:                 if ($file_version ne '') {
                   2771:                 # a versioned file is found  so save it for later
                   2772:                 if ($file_version > $version) {
                   2773: 		    $version = $file_version;
                   2774: 	        }
                   2775:             }
                   2776:         }
                   2777:     } 
                   2778:     $version ++;
                   2779:     return($version);
                   2780: }
                   2781: 
1.305     banghart 2782: sub version_selected_portfile {
1.306     banghart 2783:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2784:     my ($answer_name,$answer_ver,$answer_ext) =
                   2785:         &file_name_version_ext($file_name);
                   2786:     my $new_answer;
                   2787:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2788:     if($env{'form.copy'} eq '-1') {
                   2789:         &Apache::lonnet::logthis('problem getting file '.$file_name);
                   2790:         $new_answer = 'problem getting file';
                   2791:     } else {
                   2792:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2793:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2794:                             $stu_name,$domain,'copy',
                   2795: 		        '/portfolio'.$directory.$new_answer);
                   2796:     }    
                   2797:     return ($new_answer);
1.251     banghart 2798: }
                   2799: 
1.304     albertel 2800: sub file_name_version_ext {
                   2801:     my ($file)=@_;
                   2802:     my @file_parts = split(/\./, $file);
                   2803:     my ($name,$version,$ext);
                   2804:     if (@file_parts > 1) {
                   2805: 	$ext=pop(@file_parts);
                   2806: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2807: 	    $version=pop(@file_parts);
                   2808: 	}
                   2809: 	$name=join('.',@file_parts);
                   2810:     } else {
                   2811: 	$name=join('.',@file_parts);
                   2812:     }
                   2813:     return($name,$version,$ext);
                   2814: }
                   2815: 
1.44      ng       2816: #--------------------------------------------------------------------------------------
                   2817: #
                   2818: #-------------------------- Next few routines handles grading by section or whole class
                   2819: #
                   2820: #--- Javascript to handle grading by section or whole class
1.42      ng       2821: sub viewgrades_js {
                   2822:     my ($request) = shift;
                   2823: 
1.41      ng       2824:     $request->print(<<VIEWJAVASCRIPT);
                   2825: <script type="text/javascript" language="javascript">
1.45      ng       2826:    function writePoint(partid,weight,point) {
1.125     ng       2827: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2828: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2829: 	if (point == "textval") {
1.125     ng       2830: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2831: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2832: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2833: 		var resetbox = false;
                   2834: 		for (var i=0; i<radioButton.length; i++) {
                   2835: 		    if (radioButton[i].checked) {
                   2836: 			textbox.value = i;
                   2837: 			resetbox = true;
                   2838: 		    }
                   2839: 		}
                   2840: 		if (!resetbox) {
                   2841: 		    textbox.value = "";
                   2842: 		}
                   2843: 		return;
                   2844: 	    }
1.109     matthew  2845: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2846: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2847: 				   ") greater than the weight for the part. Accept?");
                   2848: 		if (resp == false) {
                   2849: 		    textbox.value = "";
                   2850: 		    return;
                   2851: 		}
                   2852: 	    }
1.42      ng       2853: 	    for (var i=0; i<radioButton.length; i++) {
                   2854: 		radioButton[i].checked=false;
1.109     matthew  2855: 		if (parseFloat(point) == i) {
1.42      ng       2856: 		    radioButton[i].checked=true;
                   2857: 		}
                   2858: 	    }
1.41      ng       2859: 
1.42      ng       2860: 	} else {
1.125     ng       2861: 	    textbox.value = parseFloat(point);
1.42      ng       2862: 	}
1.41      ng       2863: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2864: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2865: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2866: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2867: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2868: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2869: 	    if (saveval != "correct") {
                   2870: 		scorename.value = point;
1.43      ng       2871: 		if (selname[0].selected != true) {
                   2872: 		    selname[0].selected = true;
                   2873: 		}
1.42      ng       2874: 	    }
                   2875: 	}
1.125     ng       2876: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2877:     }
                   2878: 
                   2879:     function writeRadText(partid,weight) {
1.125     ng       2880: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2881: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2882:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2883: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2884: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2885: 	    for (var i=0; i<radioButton.length; i++) {
                   2886: 		radioButton[i].checked=false;
                   2887: 
                   2888: 	    }
                   2889: 	    textbox.value = "";
                   2890: 
                   2891: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2892: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2893: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2894: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2895: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2896: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2897: 		if ((saveval != "correct") || override) {
1.42      ng       2898: 		    scorename.value = "";
1.125     ng       2899: 		    if (selval[1].selected) {
                   2900: 			selname[1].selected = true;
                   2901: 		    } else {
                   2902: 			selname[2].selected = true;
                   2903: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   2904: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   2905: 		    }
1.42      ng       2906: 		}
                   2907: 	    }
1.43      ng       2908: 	} else {
                   2909: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2910: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2911: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2912: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2913: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2914: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2915: 		if ((saveval != "correct") || override) {
1.125     ng       2916: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       2917: 		    selname[0].selected = true;
                   2918: 		}
                   2919: 	    }
                   2920: 	}	    
1.42      ng       2921:     }
                   2922: 
                   2923:     function changeSelect(partid,user) {
1.125     ng       2924: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2925: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       2926: 	var point  = textbox.value;
1.125     ng       2927: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       2928: 
1.109     matthew  2929: 	if (isNaN(point) || parseFloat(point) < 0) {
                   2930: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       2931: 	    textbox.value = "";
                   2932: 	    return;
                   2933: 	}
1.109     matthew  2934: 	if (parseFloat(point) > parseFloat(weight)) {
                   2935: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2936: 			       ") greater than the weight of the part. Accept?");
                   2937: 	    if (resp == false) {
                   2938: 		textbox.value = "";
                   2939: 		return;
                   2940: 	    }
                   2941: 	}
1.42      ng       2942: 	selval[0].selected = true;
                   2943:     }
                   2944: 
                   2945:     function changeOneScore(partid,user) {
1.125     ng       2946: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2947: 	if (selval[1].selected || selval[2].selected) {
                   2948: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   2949: 	    if (selval[2].selected) {
                   2950: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   2951: 	    }
1.269     raeburn  2952:         }
1.42      ng       2953:     }
                   2954: 
                   2955:     function resetEntry(numpart) {
                   2956: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       2957: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   2958: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   2959: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   2960: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       2961: 	    for (var i=0; i<radioButton.length; i++) {
                   2962: 		radioButton[i].checked=false;
                   2963: 
                   2964: 	    }
                   2965: 	    textbox.value = "";
                   2966: 	    selval[0].selected = true;
                   2967: 
                   2968: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2969: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2970: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2971: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2972: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   2973: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   2974: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   2975: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2976: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2977: 		if (saveselval == "excused") {
1.43      ng       2978: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       2979: 		} else {
1.43      ng       2980: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       2981: 		}
                   2982: 	    }
1.41      ng       2983: 	}
1.42      ng       2984:     }
                   2985: 
1.41      ng       2986: </script>
                   2987: VIEWJAVASCRIPT
1.42      ng       2988: }
                   2989: 
1.44      ng       2990: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       2991: sub viewgrades {
                   2992:     my ($request) = shift;
                   2993:     &viewgrades_js($request);
1.41      ng       2994: 
1.324     albertel 2995:     my ($symb) = &get_symb($request);
1.168     albertel 2996:     #need to make sure we have the correct data for later EXT calls, 
                   2997:     #thus invalidate the cache
                   2998:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 2999:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3000:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3001:     &Apache::lonnet::clear_EXT_cache_status();
                   3002: 
1.398     albertel 3003:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   3004:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       3005: 
                   3006:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3007:     $result.=&jscriptNform($symb);
1.41      ng       3008: 
1.44      ng       3009:     #beginning of class grading form
1.41      ng       3010:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3011: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3012: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3013: 	&build_section_inputs().
1.257     albertel 3014: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   3015: 	'<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
                   3016: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3017: 
1.126     ng       3018:     my $sectionClass;
1.430     banghart 3019:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3020:     if ($env{'form.section'} eq 'all') {
1.126     ng       3021: 	$sectionClass='Class </h3>';
1.257     albertel 3022:     } elsif ($env{'form.section'} eq 'none') {
1.431     banghart 3023: 	$sectionClass=&mt('Students in no Section').'</h3>';
1.52      albertel 3024:     } else {
1.431     banghart 3025: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
1.52      albertel 3026:     }
1.431     banghart 3027:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
1.52      albertel 3028:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   3029: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       3030:     #radio buttons/text box for assigning points for a section or class.
                   3031:     #handles different parts of a problem
1.375     albertel 3032:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3033:     my %weight = ();
                   3034:     my $ctsparts = 0;
1.41      ng       3035:     $result.='<table border="0">';
1.45      ng       3036:     my %seen = ();
1.375     albertel 3037:     my @part_response_id = &flatten_responseType($responseType);
                   3038:     foreach my $part_response_id (@part_response_id) {
                   3039:     	my ($partid,$respid) = @{ $part_response_id };
                   3040: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3041: 	next if $seen{$partid};
                   3042: 	$seen{$partid}++;
1.375     albertel 3043: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3044: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3045: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3046: 
1.44      ng       3047: 	$result.='<input type="hidden" name="partid_'.
                   3048: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3049: 	$result.='<input type="hidden" name="weight_'.
                   3050: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3051: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 3052: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3053: 	$result.='<table border="0"><tr>';  
1.41      ng       3054: 	my $ctr = 0;
1.42      ng       3055: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3056: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3057: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3058: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3059: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3060: 	    $ctr++;
                   3061: 	}
                   3062: 	$result.='</tr></table>';
1.44      ng       3063: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3064: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3065: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3066: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   3067: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3068: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3069: 		$weight{$partid}.')"> '.
1.401     albertel 3070: 	    '<option selected="selected"> </option>'.
1.125     ng       3071: 	    '<option>excused</option>'.
1.265     www      3072: 	    '<option>reset status</option></select></td>'.
1.266     albertel 3073:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       3074: 	$ctsparts++;
1.41      ng       3075:     }
1.52      albertel 3076:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   3077: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3078:     $result.='<input type="button" value="Revert to Default" '.
1.417     albertel 3079: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
1.41      ng       3080: 
1.44      ng       3081:     #table listing all the students in a section/class
                   3082:     #header of table
1.126     ng       3083:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       3084:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       3085: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       3086: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 3087:     my (@parts) = sort(&getpartlist($symb));
                   3088:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3089:     my @partids = ();
1.41      ng       3090:     foreach my $part (@parts) {
                   3091: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3092: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3093: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3094: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3095:         push(@partids, $partid);
1.324     albertel 3096: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3097: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 3098: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   3099: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       3100: 	    next;
1.207     albertel 3101: 	} else {
                   3102: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3103: 	}
1.53      albertel 3104: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 3105: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       3106:     }
                   3107:     $result.='</tr>';
1.44      ng       3108: 
1.270     albertel 3109:     my %last_resets = 
                   3110: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3111: 
1.41      ng       3112:     #get info for each student
1.44      ng       3113:     #list all the students - with points and grade status
1.257     albertel 3114:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3115:     my $ctr = 0;
1.294     albertel 3116:     foreach (sort 
                   3117: 	     {
                   3118: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3119: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3120: 		 }
                   3121: 		 return $a cmp $b;
                   3122: 	     } (keys(%$fullname))) {
1.126     ng       3123: 	$ctr++;
1.324     albertel 3124: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3125: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3126:     }
                   3127:     $result.='</table></td></tr></table>';
                   3128:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3129:     $result.='<input type="button" value="Save" '.
1.417     albertel 3130: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3131:     if (scalar(%$fullname) eq 0) {
                   3132: 	my $colspan=3+scalar(@parts);
1.433     banghart 3133: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3134: 	$result='<span class="LC_warning">'.
                   3135: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
                   3136: 	        $section_display, $env{'form.Status'}).
                   3137: 	    '</span>';
1.96      albertel 3138:     }
1.324     albertel 3139:     $result.=&show_grading_menu_form($symb);
1.41      ng       3140:     return $result;
                   3141: }
                   3142: 
1.44      ng       3143: #--- call by previous routine to display each student
1.41      ng       3144: sub viewstudentgrade {
1.324     albertel 3145:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3146:     my ($uname,$udom) = split(/:/,$student);
                   3147:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3148:     my %aggregates = (); 
1.233     albertel 3149:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3150: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3151: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3152: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3153: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3154: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3155:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3156:     foreach my $apart (@$parts) {
                   3157: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3158: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3159:         $result.='<td align="center">';
1.269     raeburn  3160:         my ($aggtries,$totaltries);
                   3161:         unless (exists($aggregates{$part})) {
1.270     albertel 3162: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3163: 
                   3164: 	    $aggtries = $totaltries;
1.269     raeburn  3165:             if ($$last_resets{$part}) {  
1.270     albertel 3166:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3167: 					   $part);
                   3168:             }
1.269     raeburn  3169:             $result.='<input type="hidden" name="'.
                   3170:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3171:             $result.='<input type="hidden" name="'.
                   3172:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3173:             $aggregates{$part} = 1;
                   3174:         }
1.41      ng       3175: 	if ($type eq 'awarded') {
1.320     albertel 3176: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3177: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3178: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3179: 	    $result.='<input type="text" name="'.
1.89      albertel 3180: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3181: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3182: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3183: 	} elsif ($type eq 'solved') {
                   3184: 	    my ($status,$foo)=split(/_/,$score,2);
                   3185: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3186: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3187: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3188: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3189: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3190: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3191: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3192: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3193: 	    $result.='<option>reset status</option>';
1.126     ng       3194: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3195: 	} else {
                   3196: 	    $result.='<input type="hidden" name="'.
                   3197: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3198: 		    "\n";
1.233     albertel 3199: 	    $result.='<input type="text" name="'.
1.122     ng       3200: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3201: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3202: 	}
                   3203:     }
                   3204:     $result.='</tr>';
                   3205:     return $result;
1.38      ng       3206: }
                   3207: 
1.44      ng       3208: #--- change scores for all the students in a section/class
                   3209: #    record does not get update if unchanged
1.38      ng       3210: sub editgrades {
1.41      ng       3211:     my ($request) = @_;
                   3212: 
1.324     albertel 3213:     my $symb=&get_symb($request);
1.433     banghart 3214:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3215:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
                   3216:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
                   3217:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3218: 
1.44      ng       3219:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3220:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3221: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3222: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3223: 
                   3224:     my %scoreptr = (
                   3225: 		    'correct'  =>'correct_by_override',
                   3226: 		    'incorrect'=>'incorrect_by_override',
                   3227: 		    'excused'  =>'excused',
                   3228: 		    'ungraded' =>'ungraded_attempted',
                   3229: 		    'nothing'  => '',
                   3230: 		    );
1.257     albertel 3231:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3232: 
1.44      ng       3233:     my (@partid);
                   3234:     my %weight = ();
1.54      albertel 3235:     my %columns = ();
1.44      ng       3236:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3237: 
1.324     albertel 3238:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3239:     my $header;
1.257     albertel 3240:     while ($ctr < $env{'form.totalparts'}) {
                   3241: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3242: 	push @partid,$partid;
1.257     albertel 3243: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3244: 	$ctr++;
1.54      albertel 3245:     }
1.324     albertel 3246:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3247:     foreach my $partid (@partid) {
                   3248: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3249: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3250: 	$columns{$partid}=2;
                   3251: 	foreach my $stores (@parts) {
                   3252: 	    my ($part,$type) = &split_part_type($stores);
                   3253: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3254: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3255: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3256: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3257: 	    $display =~ s/Number of Attempts/Tries/;
                   3258: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3259: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3260: 	    $columns{$partid}+=2;
                   3261: 	}
                   3262:     }
                   3263:     foreach my $partid (@partid) {
1.324     albertel 3264: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3265: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3266: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3267: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3268: 
1.44      ng       3269:     }
                   3270:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3271:     $result .= $header;
1.44      ng       3272:     $result .= '</tr>'."\n";
1.93      albertel 3273:     my $noupdate;
1.126     ng       3274:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3275:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3276: 	my $line;
1.257     albertel 3277: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3278: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3279: 	my %newrecord;
                   3280: 	my $updateflag = 0;
1.281     albertel 3281: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3282: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3283: 	if (!&canmodify($usec)) {
1.126     ng       3284: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3285: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3286: 	    next;
                   3287: 	}
1.269     raeburn  3288:         my %aggregate = ();
                   3289:         my $aggregateflag = 0;
1.281     albertel 3290: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3291: 	foreach (@partid) {
1.257     albertel 3292: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3293: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3294: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3295: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3296: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3297: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3298: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3299: 	    my $score;
                   3300: 	    if ($partial eq '') {
1.257     albertel 3301: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3302: 	    } elsif ($partial > 0) {
                   3303: 		$score = 'correct_by_override';
                   3304: 	    } elsif ($partial == 0) {
                   3305: 		$score = 'incorrect_by_override';
                   3306: 	    }
1.257     albertel 3307: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3308: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3309: 
1.292     albertel 3310: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3311: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3312: 	    if ($dropMenu eq 'reset status' &&
                   3313: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3314: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3315: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3316: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3317: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3318: 		$updateflag = 1;
1.269     raeburn  3319:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3320:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3321:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3322:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3323:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3324:                     $aggregateflag = 1;
                   3325:                 }
1.139     albertel 3326: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3327: 		$updateflag = 1;
                   3328: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3329: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3330: 		$rec_update++;
1.125     ng       3331: 	    }
                   3332: 
1.93      albertel 3333: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3334: 		'<td align="center">'.$awarded.
                   3335: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3336: 
1.54      albertel 3337: 
                   3338: 	    my $partid=$_;
                   3339: 	    foreach my $stores (@parts) {
                   3340: 		my ($part,$type) = &split_part_type($stores);
                   3341: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3342: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3343: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3344: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3345: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3346: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3347: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3348: 		    $updateflag=1;
                   3349: 		}
1.93      albertel 3350: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3351: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3352: 	    }
1.44      ng       3353: 	}
1.93      albertel 3354: 	$line.='</tr>'."\n";
1.301     albertel 3355: 
                   3356: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3357: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3358: 
1.44      ng       3359: 	if ($updateflag) {
                   3360: 	    $count++;
1.257     albertel 3361: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3362: 				    $udom,$uname);
1.301     albertel 3363: 
                   3364: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3365: 					      $cnum,$udom,$uname)) {
                   3366: 		# need to figure out if should be in queue.
                   3367: 		my %record =  
                   3368: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3369: 					     $udom,$uname);
                   3370: 		my $all_graded = 1;
                   3371: 		my $none_graded = 1;
                   3372: 		foreach my $part (@parts) {
                   3373: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3374: 			$all_graded = 0;
                   3375: 		    } else {
                   3376: 			$none_graded = 0;
                   3377: 		    }
                   3378: 		}
                   3379: 
                   3380: 		if ($all_graded || $none_graded) {
                   3381: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3382: 							   $symb,$cdom,$cnum,
                   3383: 							   $udom,$uname);
                   3384: 		}
                   3385: 	    }
                   3386: 
1.126     ng       3387: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3388: 	    $updateCtr++;
1.93      albertel 3389: 	} else {
1.126     ng       3390: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3391: 	    $noupdateCtr++;
1.44      ng       3392: 	}
1.269     raeburn  3393:         if ($aggregateflag) {
                   3394:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3395: 				  $cdom,$cnum);
1.269     raeburn  3396:         }
1.93      albertel 3397:     }
                   3398:     if ($noupdate) {
1.126     ng       3399: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3400: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3401: 	$result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr><tr bgcolor="#ffffde">'.$noupdate;
1.44      ng       3402:     }
1.72      ng       3403:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3404: 	&show_grading_menu_form ($symb);
1.125     ng       3405:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3406: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3407: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3408:     return $title.$msg.$result;
1.5       albertel 3409: }
1.54      albertel 3410: 
                   3411: sub split_part_type {
                   3412:     my ($partstr) = @_;
                   3413:     my ($temp,@allparts)=split(/_/,$partstr);
                   3414:     my $type=pop(@allparts);
1.439     albertel 3415:     my $part=join('_',@allparts);
1.54      albertel 3416:     return ($part,$type);
                   3417: }
                   3418: 
1.44      ng       3419: #------------- end of section for handling grading by section/class ---------
                   3420: #
                   3421: #----------------------------------------------------------------------------
                   3422: 
1.5       albertel 3423: 
1.44      ng       3424: #----------------------------------------------------------------------------
                   3425: #
                   3426: #-------------------------- Next few routines handles grading by csv upload
                   3427: #
                   3428: #--- Javascript to handle csv upload
1.27      albertel 3429: sub csvupload_javascript_reverse_associate {
1.246     albertel 3430:     my $error1=&mt('You need to specify the username or ID');
                   3431:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3432:   return(<<ENDPICK);
                   3433:   function verify(vf) {
                   3434:     var foundsomething=0;
                   3435:     var founduname=0;
1.243     albertel 3436:     var foundID=0;
1.27      albertel 3437:     for (i=0;i<=vf.nfields.value;i++) {
                   3438:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3439:       if (i==0 && tw!=0) { foundID=1; }
                   3440:       if (i==1 && tw!=0) { founduname=1; }
                   3441:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3442:     }
1.246     albertel 3443:     if (founduname==0 && foundID==0) {
                   3444: 	alert('$error1');
                   3445: 	return;
1.27      albertel 3446:     }
                   3447:     if (foundsomething==0) {
1.246     albertel 3448: 	alert('$error2');
                   3449: 	return;
1.27      albertel 3450:     }
                   3451:     vf.submit();
                   3452:   }
                   3453:   function flip(vf,tf) {
                   3454:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3455:     var i;
                   3456:     for (i=0;i<=vf.nfields.value;i++) {
                   3457:       //can not pick the same destination field for both name and domain
                   3458:       if (((i ==0)||(i ==1)) && 
                   3459:           ((tf==0)||(tf==1)) && 
                   3460:           (i!=tf) &&
                   3461:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3462:         eval('vf.f'+i+'.selectedIndex=0;')
                   3463:       }
                   3464:     }
                   3465:   }
                   3466: ENDPICK
                   3467: }
                   3468: 
                   3469: sub csvupload_javascript_forward_associate {
1.246     albertel 3470:     my $error1=&mt('You need to specify the username or ID');
                   3471:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3472:   return(<<ENDPICK);
                   3473:   function verify(vf) {
                   3474:     var foundsomething=0;
                   3475:     var founduname=0;
1.243     albertel 3476:     var foundID=0;
1.27      albertel 3477:     for (i=0;i<=vf.nfields.value;i++) {
                   3478:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3479:       if (tw==1) { foundID=1; }
                   3480:       if (tw==2) { founduname=1; }
                   3481:       if (tw>3) { foundsomething=1; }
1.27      albertel 3482:     }
1.246     albertel 3483:     if (founduname==0 && foundID==0) {
                   3484: 	alert('$error1');
                   3485: 	return;
1.27      albertel 3486:     }
                   3487:     if (foundsomething==0) {
1.246     albertel 3488: 	alert('$error2');
                   3489: 	return;
1.27      albertel 3490:     }
                   3491:     vf.submit();
                   3492:   }
                   3493:   function flip(vf,tf) {
                   3494:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3495:     var i;
                   3496:     //can not pick the same destination field twice
                   3497:     for (i=0;i<=vf.nfields.value;i++) {
                   3498:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3499:         eval('vf.f'+i+'.selectedIndex=0;')
                   3500:       }
                   3501:     }
                   3502:   }
                   3503: ENDPICK
                   3504: }
                   3505: 
1.26      albertel 3506: sub csvuploadmap_header {
1.324     albertel 3507:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3508:     my $javascript;
1.257     albertel 3509:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3510: 	$javascript=&csvupload_javascript_reverse_associate();
                   3511:     } else {
                   3512: 	$javascript=&csvupload_javascript_forward_associate();
                   3513:     }
1.45      ng       3514: 
1.324     albertel 3515:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3516:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3517:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3518:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3519:     $request->print(<<ENDPICK);
1.26      albertel 3520: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3521: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3522: $result
1.326     albertel 3523: <hr />
1.26      albertel 3524: <h3>Identify fields</h3>
                   3525: Total number of records found in file: $distotal <hr />
                   3526: Enter as many fields as you can. The system will inform you and bring you back
                   3527: to this page if the data selected is insufficient to run your class.<hr />
                   3528: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3529: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3530: <input type="hidden" name="associate"  value="" />
                   3531: <input type="hidden" name="phase"      value="three" />
                   3532: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3533: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3534: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3535: <input type="hidden" name="upfile_associate" 
1.257     albertel 3536:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3537: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3538: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3539: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3540: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3541: <hr />
                   3542: <script type="text/javascript" language="Javascript">
                   3543: $javascript
                   3544: </script>
                   3545: ENDPICK
1.118     ng       3546:     return '';
1.26      albertel 3547: 
                   3548: }
                   3549: 
                   3550: sub csvupload_fields {
1.324     albertel 3551:     my ($symb) = @_;
                   3552:     my (@parts) = &getpartlist($symb);
1.243     albertel 3553:     my @fields=(['ID','Student ID'],
                   3554: 		['username','Student Username'],
                   3555: 		['domain','Student Domain']);
1.324     albertel 3556:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3557:     foreach my $part (sort(@parts)) {
                   3558: 	my @datum;
                   3559: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3560: 	my $name=$part;
                   3561: 	if  (!$display) { $display = $name; }
                   3562: 	@datum=($name,$display);
1.244     albertel 3563: 	if ($name=~/^stores_(.*)_awarded/) {
                   3564: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3565: 	}
1.41      ng       3566: 	push(@fields,\@datum);
                   3567:     }
                   3568:     return (@fields);
1.26      albertel 3569: }
                   3570: 
                   3571: sub csvuploadmap_footer {
1.41      ng       3572:     my ($request,$i,$keyfields) =@_;
                   3573:     $request->print(<<ENDPICK);
1.26      albertel 3574: </table>
                   3575: <input type="hidden" name="nfields" value="$i" />
                   3576: <input type="hidden" name="keyfields" value="$keyfields" />
                   3577: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3578: </form>
                   3579: ENDPICK
                   3580: }
                   3581: 
1.283     albertel 3582: sub checkforfile_js {
1.86      ng       3583:     my $result =<<CSVFORMJS;
                   3584: <script type="text/javascript" language="javascript">
                   3585:     function checkUpload(formname) {
                   3586: 	if (formname.upfile.value == "") {
                   3587: 	    alert("Please use the browse button to select a file from your local directory.");
                   3588: 	    return false;
                   3589: 	}
                   3590: 	formname.submit();
                   3591:     }
                   3592:     </script>
                   3593: CSVFORMJS
1.283     albertel 3594:     return $result;
                   3595: }
                   3596: 
                   3597: sub upcsvScores_form {
                   3598:     my ($request) = shift;
1.324     albertel 3599:     my ($symb)=&get_symb($request);
1.283     albertel 3600:     if (!$symb) {return '';}
                   3601:     my $result=&checkforfile_js();
1.257     albertel 3602:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3603:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3604:     $result.=$table;
1.326     albertel 3605:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3606:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3607:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3608: 	'.</b></td></tr>'."\n";
                   3609:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3610:     my $upload=&mt("Upload Scores");
1.86      ng       3611:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3612:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3613:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3614:     $result.=<<ENDUPFORM;
1.106     albertel 3615: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3616: <input type="hidden" name="symb" value="$symb" />
                   3617: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3618: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3619: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3620: $upfile_select
1.370     www      3621: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3622: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3623: </form>
                   3624: ENDUPFORM
1.370     www      3625:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3626:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3627:     .'</td></tr></table>'."\n";
1.86      ng       3628:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3629:     $result.=&show_grading_menu_form($symb);
1.86      ng       3630:     return $result;
                   3631: }
                   3632: 
                   3633: 
1.26      albertel 3634: sub csvuploadmap {
1.41      ng       3635:     my ($request)= @_;
1.324     albertel 3636:     my ($symb)=&get_symb($request);
1.41      ng       3637:     if (!$symb) {return '';}
1.72      ng       3638: 
1.41      ng       3639:     my $datatoken;
1.257     albertel 3640:     if (!$env{'form.datatoken'}) {
1.41      ng       3641: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3642:     } else {
1.257     albertel 3643: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3644: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3645:     }
1.41      ng       3646:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3647:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3648:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3649:     my ($i,$keyfields);
                   3650:     if (@records) {
1.324     albertel 3651: 	my @fields=&csvupload_fields($symb);
1.45      ng       3652: 
1.257     albertel 3653: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3654: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3655: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3656: 							  \@fields);
                   3657: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3658: 	    chop($keyfields);
                   3659: 	} else {
                   3660: 	    unshift(@fields,['none','']);
                   3661: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3662: 							    \@fields);
1.311     banghart 3663:             foreach my $rec (@records) {
                   3664:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3665:                 if (%temp) {
                   3666:                     $keyfields=join(',',sort(keys(%temp)));
                   3667:                     last;
                   3668:                 }
                   3669:             }
1.41      ng       3670: 	}
                   3671:     }
                   3672:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3673:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3674: 
1.41      ng       3675:     return '';
1.27      albertel 3676: }
                   3677: 
1.246     albertel 3678: sub csvuploadoptions {
1.41      ng       3679:     my ($request)= @_;
1.324     albertel 3680:     my ($symb)=&get_symb($request);
1.257     albertel 3681:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3682:     my $ignore=&mt('Ignore First Line');
                   3683:     $request->print(<<ENDPICK);
                   3684: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3685: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3686: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3687: <!--
1.246     albertel 3688: <p>
                   3689: <label>
                   3690:    <input type="checkbox" name="show_full_results" />
                   3691:    Show a table of all changes
                   3692: </label>
                   3693: </p>
1.302     albertel 3694: -->
1.246     albertel 3695: <p>
                   3696: <label>
                   3697:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3698:    Overwrite any existing score
                   3699: </label>
                   3700: </p>
                   3701: ENDPICK
                   3702:     my %fields=&get_fields();
                   3703:     if (!defined($fields{'domain'})) {
1.257     albertel 3704: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3705: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3706:     }
1.257     albertel 3707:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3708: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3709: 	my $cleankey=$1;
                   3710: 	if ($cleankey eq 'command') { next; }
                   3711: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3712: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3713:     }
                   3714:     # FIXME do a check for any duplicated user ids...
                   3715:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3716:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3717: <hr /></form>'."\n");
1.324     albertel 3718:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3719:     return '';
                   3720: }
                   3721: 
                   3722: sub get_fields {
                   3723:     my %fields;
1.257     albertel 3724:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3725:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3726: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3727: 	    if ($env{'form.f'.$i} ne 'none') {
                   3728: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3729: 	    }
                   3730: 	} else {
1.257     albertel 3731: 	    if ($env{'form.f'.$i} ne 'none') {
                   3732: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3733: 	    }
                   3734: 	}
1.27      albertel 3735:     }
1.246     albertel 3736:     return %fields;
                   3737: }
                   3738: 
                   3739: sub csvuploadassign {
                   3740:     my ($request)= @_;
1.324     albertel 3741:     my ($symb)=&get_symb($request);
1.246     albertel 3742:     if (!$symb) {return '';}
1.345     bowersj2 3743:     my $error_msg = '';
1.246     albertel 3744:     &Apache::loncommon::load_tmp_file($request);
                   3745:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3746:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3747:     my %fields=&get_fields();
1.41      ng       3748:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3749:     my $courseid=$env{'request.course.id'};
1.97      albertel 3750:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3751:     my @notallowed;
1.41      ng       3752:     my @skipped;
                   3753:     my $countdone=0;
                   3754:     foreach my $grade (@gradedata) {
                   3755: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3756: 	my $domain;
                   3757: 	if ($entries{$fields{'domain'}}) {
                   3758: 	    $domain=$entries{$fields{'domain'}};
                   3759: 	} else {
1.257     albertel 3760: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3761: 	}
1.243     albertel 3762: 	$domain=~s/\s//g;
1.41      ng       3763: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3764: 	$username=~s/\s//g;
1.243     albertel 3765: 	if (!$username) {
                   3766: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3767: 	    $id=~s/\s//g;
1.243     albertel 3768: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3769: 	    $username=$ids{$id};
                   3770: 	}
1.41      ng       3771: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3772: 	    my $id=$entries{$fields{'ID'}};
                   3773: 	    $id=~s/\s//g;
                   3774: 	    if ($id) {
                   3775: 		push(@skipped,"$id:$domain");
                   3776: 	    } else {
                   3777: 		push(@skipped,"$username:$domain");
                   3778: 	    }
1.41      ng       3779: 	    next;
                   3780: 	}
1.108     albertel 3781: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3782: 	if (!&canmodify($usec)) {
                   3783: 	    push(@notallowed,"$username:$domain");
                   3784: 	    next;
                   3785: 	}
1.244     albertel 3786: 	my %points;
1.41      ng       3787: 	my %grades;
                   3788: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3789: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3790: 		$dest eq 'domain') { next; }
                   3791: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3792: 	    if ($dest=~/stores_(.*)_points/) {
                   3793: 		my $part=$1;
                   3794: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3795: 					      $symb,$domain,$username);
1.345     bowersj2 3796:                 if ($wgt) {
                   3797:                     $entries{$fields{$dest}}=~s/\s//g;
                   3798:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3799:                     my $award='correct_by_override';
                   3800:                     $grades{"resource.$part.awarded"}=$pcr;
                   3801:                     $grades{"resource.$part.solved"}=$award;
                   3802:                     $points{$part}=1;
                   3803:                 } else {
                   3804:                     $error_msg = "<br />" .
                   3805:                         &mt("Some point values were assigned"
                   3806:                             ." for problems with a weight "
                   3807:                             ."of zero. These values were "
                   3808:                             ."ignored.");
                   3809:                 }
1.244     albertel 3810: 	    } else {
                   3811: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3812: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3813: 		my $store_key=$dest;
                   3814: 		$store_key=~s/^stores/resource/;
                   3815: 		$store_key=~s/_/\./g;
                   3816: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3817: 	    }
1.41      ng       3818: 	}
1.398     albertel 3819: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3820: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.244     albertel 3821: #	&Apache::lonnet::logthis(" storing ".(join('-',%grades)));
1.302     albertel 3822: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3823: 					   $env{'request.course.id'},
                   3824: 					   $domain,$username);
                   3825: 	if ($result eq 'ok') {
                   3826: 	    $request->print('.');
                   3827: 	} else {
                   3828: 	    $request->print("<p>
1.398     albertel 3829:                               <span class=\"LC_error\">
                   3830:                                  Failed to save student $username:$domain.
                   3831:                                  Message when trying to save was ($result)
                   3832:                               </span>
1.302     albertel 3833:                              </p>" );
                   3834: 	}
1.41      ng       3835: 	$request->rflush();
                   3836: 	$countdone++;
                   3837:     }
1.398     albertel 3838:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3839:     if (@skipped) {
1.398     albertel 3840: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3841: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3842:     }
                   3843:     if (@notallowed) {
1.398     albertel 3844: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3845: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3846:     }
1.106     albertel 3847:     $request->print("<br />\n");
1.324     albertel 3848:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3849:     return $error_msg;
1.26      albertel 3850: }
1.44      ng       3851: #------------- end of section for handling csv file upload ---------
                   3852: #
                   3853: #-------------------------------------------------------------------
                   3854: #
1.122     ng       3855: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3856: #
                   3857: #--- Select a page/sequence and a student to grade
1.68      ng       3858: sub pickStudentPage {
                   3859:     my ($request) = shift;
                   3860: 
                   3861:     $request->print(<<LISTJAVASCRIPT);
                   3862: <script type="text/javascript" language="javascript">
                   3863: 
                   3864: function checkPickOne(formname) {
1.76      ng       3865:     if (radioSelection(formname.student) == null) {
1.68      ng       3866: 	alert("Please select the student you wish to grade.");
                   3867: 	return;
                   3868:     }
1.125     ng       3869:     ptr = pullDownSelection(formname.selectpage);
                   3870:     formname.page.value = formname["page"+ptr].value;
                   3871:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3872:     formname.submit();
                   3873: }
                   3874: 
                   3875: </script>
                   3876: LISTJAVASCRIPT
1.118     ng       3877:     &commonJSfunctions($request);
1.324     albertel 3878:     my ($symb) = &get_symb($request);
1.257     albertel 3879:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3880:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3881:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3882: 
1.398     albertel 3883:     my $result='<h3><span class="LC_info">&nbsp;'.
                   3884: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       3885: 
1.80      ng       3886:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3887:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 3888:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 3889:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3890: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3891: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3892:     my $ctr=0;
1.68      ng       3893:     foreach (@$titles) {
                   3894: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3895: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 3896: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       3897: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3898: 	$ctr++;
1.68      ng       3899:     }
1.326     albertel 3900:     $result.= '</select>'."<br />\n";
1.70      ng       3901:     $ctr=0;
                   3902:     foreach (@$titles) {
                   3903: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3904: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3905: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3906: 	$ctr++;
                   3907:     }
1.72      ng       3908:     $result.='<input type="hidden" name="page" />'."\n".
                   3909: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3910: 
1.401     albertel 3911:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 3912: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       3913: 
1.71      ng       3914:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 3915: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 3916: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 3917: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.432     banghart 3918:     
                   3919:     $result.=&build_section_inputs();
                   3920:     $result.='<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.72      ng       3921: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 3922: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 3923: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       3924: 
1.382     albertel 3925:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   3926: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   3927: 
1.80      ng       3928:     $result.='&nbsp;<input type="button" '.
1.126     ng       3929: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       3930: 
1.68      ng       3931:     $request->print($result);
                   3932: 
1.326     albertel 3933:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       3934: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3935: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       3936: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3937: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       3938: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3939: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       3940:  
1.76      ng       3941:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       3942:     my $ptr = 1;
1.294     albertel 3943:     foreach my $student (sort 
                   3944: 			 {
                   3945: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3946: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3947: 			     }
                   3948: 			     return $a cmp $b;
                   3949: 			 } (keys(%$fullname))) {
1.68      ng       3950: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       3951: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   3952: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 3953: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   3954: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       3955: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       3956: 	$ptr++;
                   3957:     }
1.381     albertel 3958:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   3959:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       3960:     $studentTable.='<input type="button" '.
                   3961: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       3962: 
1.324     albertel 3963:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       3964:     $request->print($studentTable);
                   3965: 
                   3966:     return '';
                   3967: }
                   3968: 
                   3969: sub getSymbMap {
1.132     bowersj2 3970:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       3971: 
                   3972:     my %symbx = ();
                   3973:     my @titles = ();
1.117     bowersj2 3974:     my $minder = 0;
                   3975: 
                   3976:     # Gather every sequence that has problems.
1.240     albertel 3977:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   3978: 					       1,0,1);
1.117     bowersj2 3979:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 3980: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 3981: 	    my $title = $minder.'.'.
                   3982: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   3983: 	    push(@titles, $title); # minder in case two titles are identical
                   3984: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 3985: 	    $minder++;
1.241     albertel 3986: 	}
1.68      ng       3987:     }
                   3988:     return \@titles,\%symbx;
                   3989: }
                   3990: 
1.72      ng       3991: #
                   3992: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       3993: sub displayPage {
                   3994:     my ($request) = shift;
                   3995: 
1.324     albertel 3996:     my ($symb) = &get_symb($request);
1.257     albertel 3997:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3998:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3999:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4000:     my $pageTitle = $env{'form.page'};
1.103     albertel 4001:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4002:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4003:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4004: 
                   4005:     #need to make sure we have the correct data for later EXT calls, 
                   4006:     #thus invalidate the cache
                   4007:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4008:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4009:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4010:     &Apache::lonnet::clear_EXT_cache_status();
                   4011: 
1.103     albertel 4012:     if (!&canview($usec)) {
1.398     albertel 4013: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 4014: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4015: 	return;
                   4016:     }
1.398     albertel 4017:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4018:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       4019: 	'</h3>'."\n";
1.382     albertel 4020:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4021: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   4022:     } else {
                   4023: 	delete($env{'form.CODE'});
                   4024:     }
1.71      ng       4025:     &sub_page_js($request);
                   4026:     $request->print($result);
                   4027: 
1.132     bowersj2 4028:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4029:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4030:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4031:     if (!$map) {
1.398     albertel 4032: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4033: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4034: 	return; 
                   4035:     }
1.68      ng       4036:     my $iterator = $navmap->getIterator($map->map_start(),
                   4037: 					$map->map_finish());
                   4038: 
1.71      ng       4039:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4040: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4041: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4042: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4043: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4044: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4045: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4046: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4047: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4048: 
1.382     albertel 4049:     if (defined($env{'form.CODE'})) {
                   4050: 	$studentTable.=
                   4051: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4052:     }
1.381     albertel 4053:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4054: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4055: 	'/check.gif" height="16" border="0" />';
                   4056: 
1.118     ng       4057:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4058: 	' symbol.'."\n".
1.71      ng       4059: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4060: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4061: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4062: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4063: 
1.329     albertel 4064:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4065:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4066:     $iterator->next(); # skip the first BEGIN_MAP
                   4067:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4068:     while ($depth > 0) {
1.68      ng       4069:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4070:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4071: 
1.385     albertel 4072:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4073: 	    my $parts = $curRes->parts();
1.68      ng       4074:             my $title = $curRes->compTitle();
1.71      ng       4075: 	    my $symbx = $curRes->symb();
1.196     albertel 4076: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4077: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4078: 	    $studentTable.='<td valign="top">';
1.382     albertel 4079: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4080: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4081: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4082: 					     undef,'both',\%form);
1.71      ng       4083: 	    } else {
1.382     albertel 4084: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4085: 		$companswer =~ s|<form(.*?)>||g;
                   4086: 		$companswer =~ s|</form>||g;
1.71      ng       4087: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4088: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4089: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4090: #		}
1.116     ng       4091: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4092: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4093: 	    }
                   4094: 
1.257     albertel 4095: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4096: 
1.257     albertel 4097: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4098: 		if ($record{'version'} eq '') {
1.398     albertel 4099: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4100: 		} else {
1.116     ng       4101: 		    my %responseType = ();
                   4102: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4103: 			my @responseIds =$curRes->responseIds($partid);
                   4104: 			my @responseType =$curRes->responseType($partid);
                   4105: 			my %responseIds;
                   4106: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4107: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4108: 			}
                   4109: 			$responseType{$partid} = \%responseIds;
1.116     ng       4110: 		    }
1.148     albertel 4111: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4112: 
1.71      ng       4113: 		}
1.257     albertel 4114: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4115: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4116: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4117: 									$env{'request.course.id'},
1.71      ng       4118: 									'','.submission');
                   4119:  
                   4120: 	    }
1.103     albertel 4121: 	    if (&canmodify($usec)) {
                   4122: 		foreach my $partid (@{$parts}) {
                   4123: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4124: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4125: 		    $question++;
                   4126: 		}
1.196     albertel 4127: 		$prob++;
1.71      ng       4128: 	    }
                   4129: 	    $studentTable.='</td></tr>';
1.68      ng       4130: 
1.103     albertel 4131: 	}
1.68      ng       4132:         $curRes = $iterator->next();
                   4133:     }
                   4134: 
1.381     albertel 4135:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4136: 	'<input type="button" value="Save" '.
1.381     albertel 4137: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4138: 	'</form>'."\n";
1.324     albertel 4139:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4140:     $request->print($studentTable);
                   4141: 
                   4142:     return '';
1.119     ng       4143: }
                   4144: 
                   4145: sub displaySubByDates {
1.148     albertel 4146:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4147:     my $isCODE=0;
1.335     albertel 4148:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4149:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4150:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4151: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4152: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4153: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4154: 	'<td><b>Submission</b></td>'.
                   4155: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4156:     my ($version);
                   4157:     my %mark;
1.148     albertel 4158:     my %orders;
1.119     ng       4159:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4160:     if (!exists($$record{'1:timestamp'})) {
1.398     albertel 4161: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
1.147     albertel 4162:     }
1.335     albertel 4163: 
                   4164:     my $interaction;
1.119     ng       4165:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4166: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4167: 	if (exists($$record{$version.':resource.0.version'})) {
                   4168: 	    $interaction = $$record{$version.':resource.0.version'};
                   4169: 	}
                   4170: 
                   4171: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4172: 		             : "$version:resource");
                   4173: 	#&Apache::lonnet::logthis(" got $where");
1.119     ng       4174: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4175: 	if ($isCODE) {
                   4176: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4177: 	}
1.119     ng       4178: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4179: 	my @displaySub = ();
                   4180: 	foreach my $partid (@{$parts}) {
1.335     albertel 4181: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4182: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4183: 	    
                   4184: 
1.122     ng       4185: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4186: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4187: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4188: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4189: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4190: 
                   4191: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4192: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   4193: 		    #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
1.207     albertel 4194: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.398     albertel 4195: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
                   4196: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4197: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4198: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4199: 		    } else {
                   4200: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4201: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4202: 		    }
1.335     albertel 4203: 		    my $responseType=($isTask ? 'Task'
                   4204:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4205: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4206: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4207: 			$orders{$partid}->{$responseId}=
                   4208: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4209: 		    }
1.147     albertel 4210: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4211: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4212: 		}
                   4213: 	    }
1.335     albertel 4214: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4215: 		$displaySub[1].='Checked in by '.
                   4216: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4217: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4218: 		    '<br />';
                   4219: 	    }
                   4220: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4221: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4222: 		    lc($$record{"$where.$partid.award"}).' '.
                   4223: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4224: 		    '<br />';
                   4225: 	    }
1.335     albertel 4226: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4227: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4228: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4229: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4230: 		$displaySub[2].=
                   4231: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4232: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4233: 	    }
                   4234: 	}
                   4235: 	# needed because old essay regrader has not parts info
                   4236: 	if (exists $$record{"$version:resource.regrader"}) {
                   4237: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4238: 	}
                   4239: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4240: 	if ($displaySub[2]) {
                   4241: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4242: 	}
1.382     albertel 4243: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4244:     
1.119     ng       4245:     }
                   4246:     $studentTable.='</table></td></tr></table>';
                   4247:     return $studentTable;
1.71      ng       4248: }
                   4249: 
                   4250: sub updateGradeByPage {
                   4251:     my ($request) = shift;
                   4252: 
1.257     albertel 4253:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4254:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4255:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4256:     my $pageTitle = $env{'form.page'};
1.103     albertel 4257:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4258:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4259:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4260:     if (!&canmodify($usec)) {
1.398     albertel 4261: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4262: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4263: 	return;
                   4264:     }
1.398     albertel 4265:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4266:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4267: 	'</h3>'."\n";
1.70      ng       4268: 
1.68      ng       4269:     $request->print($result);
                   4270: 
1.132     bowersj2 4271:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4272:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4273:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4274:     if (!$map) {
1.398     albertel 4275: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4276: 	my ($symb)=&get_symb($request);
                   4277: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4278: 	return; 
                   4279:     }
1.71      ng       4280:     my $iterator = $navmap->getIterator($map->map_start(),
                   4281: 					$map->map_finish());
1.70      ng       4282: 
1.71      ng       4283:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4284: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4285: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4286: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4287: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4288: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4289: 
                   4290:     $iterator->next(); # skip the first BEGIN_MAP
                   4291:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4292:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4293:     while ($depth > 0) {
1.71      ng       4294:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4295:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4296: 
1.385     albertel 4297:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4298: 	    my $parts = $curRes->parts();
1.71      ng       4299:             my $title = $curRes->compTitle();
                   4300: 	    my $symbx = $curRes->symb();
1.196     albertel 4301: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4302: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4303: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4304: 
                   4305: 	    my %newrecord=();
                   4306: 	    my @displayPts=();
1.269     raeburn  4307:             my %aggregate = ();
                   4308:             my $aggregateflag = 0;
1.71      ng       4309: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4310: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4311: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4312: 
1.257     albertel 4313: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4314: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4315: 		my $partial = $newpts/$wgt;
                   4316: 		my $score;
                   4317: 		if ($partial > 0) {
                   4318: 		    $score = 'correct_by_override';
1.125     ng       4319: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4320: 		    $score = 'incorrect_by_override';
                   4321: 		}
1.257     albertel 4322: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4323: 		if ($dropMenu eq 'excused') {
1.71      ng       4324: 		    $partial = '';
                   4325: 		    $score = 'excused';
1.125     ng       4326: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4327: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4328: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4329: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4330: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4331: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4332: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4333: 		    $changeflag++;
                   4334: 		    $newpts = '';
1.269     raeburn  4335:                     
                   4336:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4337:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4338:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4339:                     if ($aggtries > 0) {
                   4340:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4341:                         $aggregateflag = 1;
                   4342:                     }
1.71      ng       4343: 		}
1.324     albertel 4344: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4345: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4346: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4347: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4348: 		    '&nbsp;<br />';
1.207     albertel 4349: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4350: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4351: 		    '&nbsp;<br />';
1.71      ng       4352: 		$question++;
1.380     albertel 4353: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4354: 
1.71      ng       4355: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4356: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4357: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4358: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4359: 
                   4360: 		$changeflag++;
                   4361: 	    }
                   4362: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4363: 		my %record = 
                   4364: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4365: 					     $udom,$uname);
                   4366: 
                   4367: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4368: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4369: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4370: 		    $newrecord{'resource.CODE'} = '';
                   4371: 		}
1.257     albertel 4372: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4373: 					$udom,$uname);
1.382     albertel 4374: 		%record = &Apache::lonnet::restore($symbx,
                   4375: 						   $env{'request.course.id'},
                   4376: 						   $udom,$uname);
1.380     albertel 4377: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4378: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4379: 	    }
1.380     albertel 4380: 	    
1.269     raeburn  4381:             if ($aggregateflag) {
                   4382:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4383:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4384:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4385:             }
1.125     ng       4386: 
1.71      ng       4387: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4388: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4389: 		'</tr>';
1.68      ng       4390: 
1.196     albertel 4391: 	    $prob++;
1.68      ng       4392: 	}
1.71      ng       4393:         $curRes = $iterator->next();
1.68      ng       4394:     }
1.98      albertel 4395: 
1.71      ng       4396:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4397:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4398:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4399: 		  'The scores were changed for '.
                   4400: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4401:     $request->print($grademsg.$studentTable);
1.68      ng       4402: 
1.70      ng       4403:     return '';
                   4404: }
                   4405: 
1.72      ng       4406: #-------- end of section for handling grading by page/sequence ---------
                   4407: #
                   4408: #-------------------------------------------------------------------
                   4409: 
1.75      albertel 4410: #--------------------Scantron Grading-----------------------------------
                   4411: #
                   4412: #------ start of section for handling grading by page/sequence ---------
                   4413: 
1.423     albertel 4414: =pod
                   4415: 
                   4416: =head1 Bubble sheet grading routines
                   4417: 
1.424     albertel 4418:   For this documentation:
                   4419: 
                   4420:    'scanline' refers to the full line of characters
                   4421:    from the file that we are parsing that represents one entire sheet
                   4422: 
                   4423:    'bubble line' refers to the data
                   4424:    representing the line of bubbles that are on the physical bubble sheet
                   4425: 
                   4426: 
                   4427: The overall process is that a scanned in bubble sheet data is uploaded
                   4428: into a course. When a user wants to grade, they select a
                   4429: sequence/folder of resources, a file of bubble sheet info, and pick
                   4430: one of the predefined configurations for what each scanline looks
                   4431: like.
                   4432: 
                   4433: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4434: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4435: because too light bubbling), 'double bubble' (each bubble line should
                   4436: have no more that one letter picked), invalid or duplicated CODE,
                   4437: invalid student ID
                   4438: 
                   4439: If the CODE option is used that determines the randomization of the
                   4440: homework problems, either way the student ID is looked up into a
                   4441: username:domain.
                   4442: 
                   4443: During the validation phase the instructor can choose to skip scanlines. 
                   4444: 
1.435     foxr     4445: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4446: 
                   4447:   scantron_original_filename (unmodified original file)
                   4448:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4449:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4450: 
                   4451: Also there is a separate hash nohist_scantrondata that contains extra
                   4452: correction information that isn't representable in the bubble sheet
                   4453: file (see &scantron_getfile() for more information)
                   4454: 
                   4455: After all scanlines are either valid, marked as valid or skipped, then
                   4456: foreach line foreach problem in the picked sequence, an ssi request is
                   4457: made that simulates a user submitting their selected letter(s) against
                   4458: the homework problem.
1.423     albertel 4459: 
                   4460: =over 4
                   4461: 
                   4462: =cut
                   4463: 
                   4464: 
                   4465: =pod 
                   4466: 
                   4467: =item defaultFormData
                   4468: 
                   4469:   Returns html hidden inputs used to hold context/default values.
                   4470: 
                   4471:  Arguments:
                   4472:   $symb - $symb of the current resource 
                   4473: 
                   4474: =cut
1.422     foxr     4475: 
1.81      albertel 4476: sub defaultFormData {
1.324     albertel 4477:     my ($symb)=@_;
1.81      albertel 4478:     return '
1.418     albertel 4479:       <input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4480:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4481:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4482: }
                   4483: 
1.423     albertel 4484: =pod 
                   4485: 
                   4486: =item getSequenceDropDown
                   4487: 
                   4488:    Return html dropdown of possible sequences to grade
                   4489:  
                   4490:  Arguments:
                   4491:    $symb - $symb of the current resource 
                   4492: 
                   4493: =cut
1.422     foxr     4494: 
1.75      albertel 4495: sub getSequenceDropDown {
1.423     albertel 4496:     my ($symb)=@_;
1.75      albertel 4497:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4498:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4499:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4500:     my $ctr=0;
                   4501:     foreach (@$titles) {
                   4502: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4503: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4504: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4505: 	    '>'.$showtitle.'</option>'."\n";
                   4506: 	$ctr++;
                   4507:     }
                   4508:     $result.= '</select>';
                   4509:     return $result;
                   4510: }
                   4511: 
1.423     albertel 4512: 
                   4513: =pod 
                   4514: 
                   4515: =item scantron_filenames
                   4516: 
                   4517:    Returns a list of the scantron files in the current course 
                   4518: 
                   4519: =cut
1.422     foxr     4520: 
1.202     albertel 4521: sub scantron_filenames {
1.257     albertel 4522:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4523:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4524:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4525: 				    &propath($cdom,$cname));
1.202     albertel 4526:     my @possiblenames;
1.201     albertel 4527:     foreach my $filename (sort(@files)) {
1.157     albertel 4528: 	($filename)=split(/&/,$filename);
                   4529: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4530: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4531: 	push(@possiblenames,$filename);
                   4532:     }
                   4533:     return @possiblenames;
                   4534: }
                   4535: 
1.423     albertel 4536: =pod 
                   4537: 
                   4538: =item scantron_uploads
                   4539: 
                   4540:    Returns  html drop-down list of scantron files in current course.
                   4541: 
                   4542:  Arguments:
                   4543:    $file2grade - filename to set as selected in the dropdown
                   4544: 
                   4545: =cut
1.422     foxr     4546: 
1.202     albertel 4547: sub scantron_uploads {
1.209     ng       4548:     my ($file2grade) = @_;
1.202     albertel 4549:     my $result=	'<select name="scantron_selectfile">';
                   4550:     $result.="<option></option>";
                   4551:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4552: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4553:     }
                   4554:     $result.="</select>";
                   4555:     return $result;
                   4556: }
                   4557: 
1.423     albertel 4558: =pod 
                   4559: 
                   4560: =item scantron_scantab
                   4561: 
                   4562:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4563:   file.
                   4564: 
                   4565: =cut
1.422     foxr     4566: 
1.82      albertel 4567: sub scantron_scantab {
                   4568:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4569:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4570:     $result.='<option></option>'."\n";
1.82      albertel 4571:     foreach my $line (<$fh>) {
                   4572: 	my ($name,$descrip)=split(/:/,$line);
                   4573: 	if ($name =~ /^\#/) { next; }
                   4574: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4575:     }
                   4576:     $result.='</select>'."\n";
                   4577: 
                   4578:     return $result;
                   4579: }
                   4580: 
1.423     albertel 4581: =pod 
                   4582: 
                   4583: =item scantron_CODElist
                   4584: 
                   4585:   Returns html drop down of the saved CODE lists from current course,
                   4586:   generated from earlier printings.
                   4587: 
                   4588: =cut
1.422     foxr     4589: 
1.186     albertel 4590: sub scantron_CODElist {
1.257     albertel 4591:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4592:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4593:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4594:     my $namechoice='<option></option>';
1.225     albertel 4595:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4596: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4597: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4598: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4599:     }
                   4600:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4601:     return $namechoice;
                   4602: }
                   4603: 
1.423     albertel 4604: =pod 
                   4605: 
                   4606: =item scantron_CODEunique
                   4607: 
                   4608:   Returns the html for "Each CODE to be used once" radio.
                   4609: 
                   4610: =cut
1.422     foxr     4611: 
1.186     albertel 4612: sub scantron_CODEunique {
1.381     albertel 4613:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4614:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4615:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4616:                 </span>
                   4617:                 <span style="white-space: nowrap;">
1.272     albertel 4618:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4619:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4620:                 </span>';
1.186     albertel 4621:     return $result;
                   4622: }
1.423     albertel 4623: 
                   4624: =pod 
                   4625: 
                   4626: =item scantron_selectphase
                   4627: 
                   4628:   Generates the initial screen to start the bubble sheet process.
                   4629:   Allows for - starting a grading run.
1.424     albertel 4630:              - downloading existing scan data (original, corrected
1.423     albertel 4631:                                                 or skipped info)
                   4632: 
                   4633:              - uploading new scan data
                   4634: 
                   4635:  Arguments:
                   4636:   $r          - The Apache request object
                   4637:   $file2grade - name of the file that contain the scanned data to score
                   4638: 
                   4639: =cut
1.186     albertel 4640: 
1.75      albertel 4641: sub scantron_selectphase {
1.209     ng       4642:     my ($r,$file2grade) = @_;
1.324     albertel 4643:     my ($symb)=&get_symb($r);
1.75      albertel 4644:     if (!$symb) {return '';}
1.423     albertel 4645:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4646:     my $default_form_data=&defaultFormData($symb);
                   4647:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4648:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4649:     my $format_selector=&scantron_scantab();
1.186     albertel 4650:     my $CODE_selector=&scantron_CODElist();
                   4651:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4652:     my $result;
1.422     foxr     4653: 
                   4654:     # Chunk of form to prompt for a file to grade and how:
                   4655: 
1.75      albertel 4656:     $result.= <<SCANTRONFORM;
1.162     albertel 4657:     <table width="100%" border="0">
1.75      albertel 4658:     <tr>
1.226     albertel 4659:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4660:       <td bgcolor="#777777">
1.203     albertel 4661:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4662:         $default_form_data
1.75      albertel 4663:         <table width="100%" border="0">
                   4664:           <tr bgcolor="#e6ffff">
1.174     albertel 4665:             <td colspan="2">
                   4666:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4667:             </td>
                   4668:           </tr>
                   4669:           <tr bgcolor="#ffffe6">
1.174     albertel 4670:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4671:           </tr>
                   4672:           <tr bgcolor="#ffffe6">
1.174     albertel 4673:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4674:           </tr>
1.82      albertel 4675:           <tr bgcolor="#ffffe6">
1.174     albertel 4676:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4677:           </tr>
1.157     albertel 4678:           <tr bgcolor="#ffffe6">
1.186     albertel 4679:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4680:           </tr>
                   4681:           <tr bgcolor="#ffffe6">
                   4682:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4683:           </tr>
                   4684:           <tr bgcolor="#ffffe6">
1.187     albertel 4685: 	    <td> Options: </td>
                   4686:             <td>
1.272     albertel 4687: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4688:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4689:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4690: 	    </td>
                   4691:           </tr>
                   4692:           <tr bgcolor="#ffffe6">
1.174     albertel 4693:             <td colspan="2">
1.265     www      4694:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4695:             </td>
                   4696:           </tr>
                   4697:         </table>
1.226     albertel 4698:        </td>
                   4699:      </form>
1.162     albertel 4700:     </tr>
                   4701: SCANTRONFORM
                   4702:    
                   4703:     $r->print($result);
                   4704: 
1.257     albertel 4705:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4706:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4707: 
1.422     foxr     4708: 	# Chunk of form to prompt for a scantron file upload.
                   4709: 
1.162     albertel 4710:         $r->print(<<SCANTRONFORM);
                   4711:     <tr>
                   4712:       <td bgcolor="#777777">
                   4713:         <table width="100%" border="0">
                   4714:           <tr bgcolor="#e6ffff">
                   4715:             <td>
1.174     albertel 4716:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4717:             </td>
                   4718:           </tr>
                   4719:           <tr bgcolor="#ffffe6">
                   4720:             <td>
                   4721: SCANTRONFORM
1.324     albertel 4722:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4723:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4724:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4725:     $r->print(<<UPLOAD);
                   4726:               <script type="text/javascript" language="javascript">
                   4727:     function checkUpload(formname) {
                   4728: 	if (formname.upfile.value == "") {
                   4729: 	    alert("Please use the browse button to select a file from your local directory.");
                   4730: 	    return false;
                   4731: 	}
                   4732: 	formname.submit();
                   4733:     }
                   4734:               </script>
                   4735: 
                   4736:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4737:                 $default_form_data
                   4738:                 <input name='courseid' type='hidden' value='$cnum' />
                   4739:                 <input name='domainid' type='hidden' value='$cdom' />
                   4740:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4741:                 File to upload:<input type="file" name="upfile" size="50" />
                   4742:                 <br />
                   4743:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4744:               </form>
                   4745: UPLOAD
1.162     albertel 4746: 
                   4747:         $r->print(<<SCANTRONFORM);
                   4748:             </td>
                   4749:           </tr>
1.75      albertel 4750:         </table>
                   4751:       </td>
                   4752:     </tr>
1.162     albertel 4753: SCANTRONFORM
                   4754:     }
1.422     foxr     4755: 
                   4756:     # Chunk of the form that prompts to view a scoring office file,
                   4757:     # corrected file, skipped records in a file.
                   4758: 
1.187     albertel 4759:     $r->print(<<SCANTRONFORM);
                   4760:     <tr>
1.226     albertel 4761:       <form action='/adm/grades' name='scantron_download'>
                   4762:         <td bgcolor="#777777">
1.379     albertel 4763: 	  $default_form_data
1.187     albertel 4764:           <input type="hidden" name="command" value="scantron_download" />
                   4765:           <table width="100%" border="0">
                   4766:             <tr bgcolor="#e6ffff">
                   4767:               <td colspan="2">
                   4768:                 &nbsp;<b>Download a scoring office file</b>
                   4769:               </td>
                   4770:             </tr>
                   4771:             <tr bgcolor="#ffffe6">
                   4772:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4773:             </tr>
                   4774:             <tr bgcolor="#ffffe6">
                   4775:               <td colspan="2">
1.293     www      4776:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4777:               </td>
                   4778:             </tr>
                   4779:           </table>
1.226     albertel 4780:         </td>
                   4781:       </form>
1.187     albertel 4782:     </tr>
                   4783: SCANTRONFORM
1.162     albertel 4784: 
                   4785:     $r->print(<<SCANTRONFORM);
1.75      albertel 4786:   </table>
1.81      albertel 4787: $grading_menu_button
1.75      albertel 4788: SCANTRONFORM
                   4789: 
1.162     albertel 4790:     return
1.75      albertel 4791: }
                   4792: 
1.423     albertel 4793: =pod
                   4794: 
                   4795: =item get_scantron_config
                   4796: 
                   4797:    Parse and return the scantron configuration line selected as a
                   4798:    hash of configuration file fields.
                   4799: 
                   4800:  Arguments:
                   4801:     which - the name of the configuration to parse from the file.
                   4802: 
                   4803: 
                   4804:  Returns:
                   4805:             If the named configuration is not in the file, an empty
                   4806:             hash is returned.
                   4807:     a hash with the fields
                   4808:       name         - internal name for the this configuration setup
                   4809:       description  - text to display to operator that describes this config
                   4810:       CODElocation - if 0 or the string 'none'
                   4811:                           - no CODE exists for this config
                   4812:                      if -1 || the string 'letter'
                   4813:                           - a CODE exists for this config and is
                   4814:                             a string of letters
                   4815:                      Unsupported value (but planned for future support)
                   4816:                           if a positive integer
                   4817:                                - The CODE exists as the first n items from
                   4818:                                  the question section of the form
                   4819:                           if the string 'number'
                   4820:                                - The CODE exists for this config and is
                   4821:                                  a string of numbers
                   4822:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4823:                      the CODE starts
                   4824:       CODElength  - length of the CODE
                   4825:       IDstart     - column where the student ID number starts
                   4826:       IDlength    - length of the student ID info
                   4827:       Qstart      - column where the information from the bubbled
                   4828:                     'questions' start
                   4829:       Qlength     - number of columns comprising a single bubble line from
                   4830:                     the sheet. (usually either 1 or 10)
1.424     albertel 4831:       Qon         - either a single character representing the character used
1.423     albertel 4832:                     to signal a bubble was chosen in the positional setup, or
                   4833:                     the string 'letter' if the letter of the chosen bubble is
                   4834:                     in the final, or 'number' if a number representing the
                   4835:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 4836:       Qoff        - the character used to represent that a bubble was
                   4837:                     left blank
1.423     albertel 4838:       PaperID     - if the scanning process generates a unique number for each
                   4839:                     sheet scanned the column that this ID number starts in
                   4840:       PaperIDlength - number of columns that comprise the unique ID number
                   4841:                       for the sheet of paper
1.424     albertel 4842:       FirstName   - column that the first name starts in
1.423     albertel 4843:       FirstNameLength - number of columns that the first name spans
                   4844:  
                   4845:       LastName    - column that the last name starts in
                   4846:       LastNameLength - number of columns that the last name spans
                   4847: 
                   4848: =cut
1.422     foxr     4849: 
1.82      albertel 4850: sub get_scantron_config {
                   4851:     my ($which) = @_;
                   4852:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4853:     my %config;
1.157     albertel 4854:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4855:     foreach my $line (<$fh>) {
                   4856: 	my ($name,$descrip)=split(/:/,$line);
                   4857: 	if ($name ne $which ) { next; }
                   4858: 	chomp($line);
                   4859: 	my @config=split(/:/,$line);
                   4860: 	$config{'name'}=$config[0];
                   4861: 	$config{'description'}=$config[1];
                   4862: 	$config{'CODElocation'}=$config[2];
                   4863: 	$config{'CODEstart'}=$config[3];
                   4864: 	$config{'CODElength'}=$config[4];
                   4865: 	$config{'IDstart'}=$config[5];
                   4866: 	$config{'IDlength'}=$config[6];
                   4867: 	$config{'Qstart'}=$config[7];
                   4868: 	$config{'Qlength'}=$config[8];
                   4869: 	$config{'Qoff'}=$config[9];
                   4870: 	$config{'Qon'}=$config[10];
1.157     albertel 4871: 	$config{'PaperID'}=$config[11];
                   4872: 	$config{'PaperIDlength'}=$config[12];
                   4873: 	$config{'FirstName'}=$config[13];
                   4874: 	$config{'FirstNamelength'}=$config[14];
                   4875: 	$config{'LastName'}=$config[15];
                   4876: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4877: 	last;
                   4878:     }
                   4879:     return %config;
                   4880: }
                   4881: 
1.423     albertel 4882: =pod 
                   4883: 
                   4884: =item username_to_idmap
                   4885: 
                   4886:     creates a hash keyed by student id with values of the corresponding
                   4887:     student username:domain.
                   4888: 
                   4889:   Arguments:
                   4890: 
                   4891:     $classlist - reference to the class list hash. This is a hash
                   4892:                  keyed by student name:domain  whose elements are references
1.424     albertel 4893:                  to arrays containing various chunks of information
1.423     albertel 4894:                  about the student. (See loncoursedata for more info).
                   4895: 
                   4896:   Returns
                   4897:     %idmap - the constructed hash
                   4898: 
                   4899: =cut
                   4900: 
1.82      albertel 4901: sub username_to_idmap {
                   4902:     my ($classlist)= @_;
                   4903:     my %idmap;
                   4904:     foreach my $student (keys(%$classlist)) {
                   4905: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4906: 	    $student;
                   4907:     }
                   4908:     return %idmap;
                   4909: }
1.423     albertel 4910: 
                   4911: =pod
                   4912: 
1.424     albertel 4913: =item scantron_fixup_scanline
1.423     albertel 4914: 
                   4915:    Process a requested correction to a scanline.
                   4916: 
                   4917:   Arguments:
                   4918:     $scantron_config   - hash from &get_scantron_config()
                   4919:     $scan_data         - hash of correction information 
                   4920:                           (see &scantron_getfile())
                   4921:     $line              - existing scanline
                   4922:     $whichline         - line number of the passed in scanline
                   4923:     $field             - type of change to process 
                   4924:                          (either 
                   4925:                           'ID'     -> correct the student ID number
                   4926:                           'CODE'   -> correct the CODE
                   4927:                           'answer' -> fixup the submitted answers)
                   4928:     
                   4929:    $args               - hash of additional info,
                   4930:                           - 'ID' 
                   4931:                                'newid' -> studentID to use in replacement
1.424     albertel 4932:                                           of existing one
1.423     albertel 4933:                           - 'CODE' 
                   4934:                                'CODE_ignore_dup' - set to true if duplicates
                   4935:                                                    should be ignored.
                   4936: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 4937:                                         if the existing unfound code should
1.423     albertel 4938:                                         be used as is
                   4939:                           - 'answer'
                   4940:                                'response' - new answer or 'none' if blank
                   4941:                                'question' - the bubble line to change
                   4942: 
                   4943:   Returns:
                   4944:     $line - the modified scanline
                   4945: 
                   4946:   Side effects: 
                   4947:     $scan_data - may be updated
                   4948: 
                   4949: =cut
                   4950: 
1.82      albertel 4951: 
1.157     albertel 4952: sub scantron_fixup_scanline {
                   4953:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.423     albertel 4954: 
1.157     albertel 4955:     if ($field eq 'ID') {
                   4956: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 4957: 	    return ($line,1,'New value too large');
1.157     albertel 4958: 	}
                   4959: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   4960: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   4961: 				     $args->{'newid'});
                   4962: 	}
                   4963: 	substr($line,$$scantron_config{'IDstart'}-1,
                   4964: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   4965: 	if ($args->{'newid'}=~/^\s*$/) {
                   4966: 	    &scan_data($scan_data,"$whichline.user",
                   4967: 		       $args->{'username'}.':'.$args->{'domain'});
                   4968: 	}
1.186     albertel 4969:     } elsif ($field eq 'CODE') {
1.192     albertel 4970: 	if ($args->{'CODE_ignore_dup'}) {
                   4971: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   4972: 	}
                   4973: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   4974: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 4975: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   4976: 		return ($line,1,'New CODE value too large');
                   4977: 	    }
                   4978: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   4979: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   4980: 	    }
                   4981: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   4982: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 4983: 	}
1.157     albertel 4984:     } elsif ($field eq 'answer') {
                   4985: 	my $length=$scantron_config->{'Qlength'};
                   4986: 	my $off=$scantron_config->{'Qoff'};
                   4987: 	my $on=$scantron_config->{'Qon'};
                   4988: 	my $answer=${off}x$length;
                   4989: 	if ($args->{'response'} eq 'none') {
                   4990: 	    &scan_data($scan_data,
                   4991: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   4992: 	} else {
1.274     albertel 4993: 	    if ($on eq 'letter') {
                   4994: 		my @alphabet=('A'..'Z');
                   4995: 		$answer=$alphabet[$args->{'response'}];
                   4996: 	    } elsif ($on eq 'number') {
                   4997: 		$answer=$args->{'response'}+1;
1.389     albertel 4998: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 4999: 	    } else {
                   5000: 		substr($answer,$args->{'response'},1)=$on;
                   5001: 	    }
1.157     albertel 5002: 	    &scan_data($scan_data,
                   5003: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   5004: 	}
                   5005: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5006: 	substr($line,$where-1,$length)=$answer;
                   5007:     }
                   5008:     return $line;
                   5009: }
1.423     albertel 5010: 
                   5011: =pod
                   5012: 
                   5013: =item scan_data
                   5014: 
                   5015:     Edit or look up  an item in the scan_data hash.
                   5016: 
                   5017:   Arguments:
                   5018:     $scan_data  - The hash (see scantron_getfile)
                   5019:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5020:                   scantronfilename_key).
1.423     albertel 5021:     $data        - New value of the hash entry.
                   5022:     $delete      - If true, the entry is removed from the hash.
                   5023: 
                   5024:   Returns:
                   5025:     The new value of the hash table field (undefined if deleted).
                   5026: 
                   5027: =cut
                   5028: 
                   5029: 
1.157     albertel 5030: sub scan_data {
                   5031:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5032:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5033:     if (defined($value)) {
                   5034: 	$scan_data->{$filename.'_'.$key} = $value;
                   5035:     }
                   5036:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5037:     return $scan_data->{$filename.'_'.$key};
                   5038: }
1.423     albertel 5039: 
                   5040: =pod 
                   5041: 
                   5042: =item scantron_parse_scanline
                   5043: 
                   5044:   Decodes a scanline from the selected scantron file
                   5045: 
                   5046:  Arguments:
                   5047:     line             - The text of the scantron file line to process
                   5048:     whichline        - Line number
                   5049:     scantron_config  - Hash describing the format of the scantron lines.
                   5050:     scan_data        - Hash of extra information about the scanline
                   5051:                        (see scantron_getfile for more information)
                   5052:     just_header      - True if should not process question answers but only
                   5053:                        the stuff to the left of the answers.
                   5054:  Returns:
                   5055:    Hash containing the result of parsing the scanline
                   5056: 
                   5057:    Keys are all proceeded by the string 'scantron.'
                   5058: 
                   5059:        CODE    - the CODE in use for this scanline
                   5060:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5061:                  by the operator
                   5062:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5063:                             CODEs were selected, but the usage has been
                   5064:                             forced by the operator
                   5065:        ID  - student ID
                   5066:        PaperID - if used, the ID number printed on the sheet when the 
                   5067:                  paper was scanned
                   5068:        FirstName - first name from the sheet
                   5069:        LastName  - last name from the sheet
                   5070: 
                   5071:      if just_header was not true these key may also exist
                   5072: 
                   5073:        missingerror - a list of bubbled line numbers that had a blank bubble
                   5074:                       that is considered an error (if the operator had already
                   5075:                       okayed a blank bubble line as really being blank then
                   5076:                       that bubble line number won't appear here.
                   5077:        doubleerror  - a list of bubbled line numbers that had more than one
                   5078:                       bubble filled in and has not been corrected by the
                   5079:                       operator
                   5080:        maxquest     - the number of the last bubble line that was parsed
                   5081: 
                   5082:        (<number> starts at 1)
                   5083:        <number>.answer - zero or more letters representing the selected
                   5084:                          letters from the scanline for the bubble line 
                   5085:                          <number>.
                   5086:                          if blank there was either no bubble or there where
                   5087:                          multiple bubbles, (consult the keys missingerror and
                   5088:                          doubleerror if this is an error condition)
                   5089: 
                   5090: =cut
                   5091: 
1.82      albertel 5092: sub scantron_parse_scanline {
1.423     albertel 5093:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.82      albertel 5094:     my %record;
1.422     foxr     5095:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5096:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5097:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5098: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5099: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5100: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5101: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5102: 	    $record{'scantron.CODE'}=substr($data,
                   5103: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5104: 					    $$scantron_config{'CODElength'});
1.191     albertel 5105: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5106: 		$record{'scantron.useCODE'}=1;
                   5107: 	    }
1.192     albertel 5108: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5109: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5110: 	    }
1.82      albertel 5111: 	} else {
                   5112: 	    #FIXME interpret first N questions
                   5113: 	}
                   5114:     }
1.83      albertel 5115:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5116: 				  $$scantron_config{'IDlength'});
1.157     albertel 5117:     $record{'scantron.PaperID'}=
                   5118: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5119: 	       $$scantron_config{'PaperIDlength'});
                   5120:     $record{'scantron.FirstName'}=
                   5121: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5122: 	       $$scantron_config{'FirstNamelength'});
                   5123:     $record{'scantron.LastName'}=
                   5124: 	substr($data,$$scantron_config{'LastName'}-1,
                   5125: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5126:     if ($just_header) { return \%record; }
1.194     albertel 5127: 
1.82      albertel 5128:     my @alphabet=('A'..'Z');
                   5129:     my $questnum=0;
                   5130:     while ($questions) {
                   5131: 	$questnum++;
                   5132: 	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
                   5133: 	substr($questions,0,$$scantron_config{'Qlength'})='';
1.83      albertel 5134: 	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
1.239     albertel 5135: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.371     albertel 5136: 	    if ($currentquest eq '?'
                   5137: 		|| $currentquest eq '*') {
1.274     albertel 5138: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5139: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 5140: 	    } elsif (!defined($currentquest)
1.274     albertel 5141: 		     || $currentquest eq $$scantron_config{'Qoff'}
                   5142: 		     || $currentquest !~ /^[A-Z]$/) {
1.239     albertel 5143: 		$record{"scantron.$questnum.answer"}='';
                   5144: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5145: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5146: 		}
                   5147: 	    } else {
                   5148: 		$record{"scantron.$questnum.answer"}=$currentquest;
                   5149: 	    }
                   5150: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.371     albertel 5151: 	    if ($currentquest eq '?'
                   5152: 		|| $currentquest eq '*') {
1.274     albertel 5153: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5154: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 5155: 	    } elsif (!defined($currentquest)
                   5156: 		     || $currentquest eq $$scantron_config{'Qoff'} 
                   5157: 		     || $currentquest !~ /^\d$/) {
1.239     albertel 5158: 		$record{"scantron.$questnum.answer"}='';
                   5159: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5160: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5161: 		}
                   5162: 	    } else {
1.371     albertel 5163: 		# wrap zero back to J
                   5164: 		if ($currentquest eq '0') {
                   5165: 		    $record{"scantron.$questnum.answer"}=
                   5166: 			$alphabet[9];
                   5167: 		} else {
                   5168: 		    $record{"scantron.$questnum.answer"}=
                   5169: 			$alphabet[$currentquest-1];
                   5170: 		}
1.239     albertel 5171: 	    }
1.82      albertel 5172: 	} else {
1.239     albertel 5173: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
                   5174: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}) {
                   5175: 		$record{"scantron.$questnum.answer"}='';
                   5176: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5177: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5178: 		}
                   5179: 	    } else {
                   5180: 		$record{"scantron.$questnum.answer"}=
                   5181: 		    $alphabet[length($array[0])];
                   5182: 	    }
                   5183: 	    if (scalar(@array) gt 2) {
                   5184: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5185: 		my @ans=@array;
                   5186: 		my $i=length($ans[0]);shift(@ans);
                   5187: 		while ($#ans) {
                   5188: 		    $i+=length($ans[0])+1;
                   5189: 		    $record{"scantron.$questnum.answer"}.=$alphabet[$i];
                   5190: 		    shift(@ans);
                   5191: 		}
                   5192: 	    }
1.82      albertel 5193: 	}
                   5194:     }
1.83      albertel 5195:     $record{'scantron.maxquest'}=$questnum;
                   5196:     return \%record;
1.82      albertel 5197: }
                   5198: 
1.423     albertel 5199: =pod
                   5200: 
                   5201: =item scantron_add_delay
                   5202: 
                   5203:    Adds an error message that occurred during the grading phase to a
                   5204:    queue of messages to be shown after grading pass is complete
                   5205: 
                   5206:  Arguments:
1.424     albertel 5207:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5208:    $scanline    - the scanline that caused the error
                   5209:    $errormesage - the error message
                   5210:    $errorcode   - a numeric code for the error
                   5211: 
                   5212:  Side Effects:
1.424     albertel 5213:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5214: 
                   5215: =cut
                   5216: 
1.82      albertel 5217: sub scantron_add_delay {
1.140     albertel 5218:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5219:     push(@$delayqueue,
                   5220: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5221: 	  'ecode' => $errorcode }
                   5222: 	 );
1.82      albertel 5223: }
                   5224: 
1.423     albertel 5225: =pod
                   5226: 
                   5227: =item scantron_find_student
                   5228: 
1.424     albertel 5229:    Finds the username for the current scanline
                   5230: 
                   5231:   Arguments:
                   5232:    $scantron_record - hash result from scantron_parse_scanline
                   5233:    $scan_data       - hash of correction information 
                   5234:                       (see &scantron_getfile() form more information)
                   5235:    $idmap           - hash from &username_to_idmap()
                   5236:    $line            - number of current scanline
                   5237:  
                   5238:   Returns:
                   5239:    Either 'username:domain' or undef if unknown
                   5240: 
1.423     albertel 5241: =cut
                   5242: 
1.82      albertel 5243: sub scantron_find_student {
1.157     albertel 5244:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5245:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5246:     if ($scanID =~ /^\s*$/) {
                   5247:  	return &scan_data($scan_data,"$line.user");
                   5248:     }
1.83      albertel 5249:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5250:  	if (lc($id) eq lc($scanID)) {
                   5251:  	    return $$idmap{$id};
                   5252:  	}
1.83      albertel 5253:     }
                   5254:     return undef;
                   5255: }
                   5256: 
1.423     albertel 5257: =pod
                   5258: 
                   5259: =item scantron_filter
                   5260: 
1.424     albertel 5261:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5262:    hidden resources was selected
                   5263: 
1.423     albertel 5264: =cut
                   5265: 
1.83      albertel 5266: sub scantron_filter {
                   5267:     my ($curres)=@_;
1.331     albertel 5268: 
                   5269:     if (ref($curres) && $curres->is_problem()) {
                   5270: 	# if the user has asked to not have either hidden
                   5271: 	# or 'randomout' controlled resources to be graded
                   5272: 	# don't include them
                   5273: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5274: 	    && $curres->randomout) {
                   5275: 	    return 0;
                   5276: 	}
1.83      albertel 5277: 	return 1;
                   5278:     }
                   5279:     return 0;
1.82      albertel 5280: }
                   5281: 
1.423     albertel 5282: =pod
                   5283: 
                   5284: =item scantron_process_corrections
                   5285: 
1.424     albertel 5286:    Gets correction information out of submitted form data and corrects
                   5287:    the scanline
                   5288: 
1.423     albertel 5289: =cut
                   5290: 
1.157     albertel 5291: sub scantron_process_corrections {
                   5292:     my ($r) = @_;
1.257     albertel 5293:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5294:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5295:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5296:     my $which=$env{'form.scantron_line'};
1.200     albertel 5297:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5298:     my ($skip,$err,$errmsg);
1.257     albertel 5299:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5300: 	$skip=1;
1.257     albertel 5301:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5302: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5303: 	    $env{'form.scantron_domain'};
1.157     albertel 5304: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5305: 	($line,$err,$errmsg)=
                   5306: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5307: 				     'ID',{'newid'=>$newid,
1.257     albertel 5308: 				    'username'=>$env{'form.scantron_username'},
                   5309: 				    'domain'=>$env{'form.scantron_domain'}});
                   5310:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5311: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5312: 	my $newCODE;
1.192     albertel 5313: 	my %args;
1.190     albertel 5314: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5315: 	    $newCODE='use_unfound';
1.190     albertel 5316: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5317: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5318: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5319: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5320: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5321: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5322: 	}
1.257     albertel 5323: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5324: 	    $args{'CODE_ignore_dup'}=1;
                   5325: 	}
                   5326: 	$args{'CODE'}=$newCODE;
1.186     albertel 5327: 	($line,$err,$errmsg)=
                   5328: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5329: 				     'CODE',\%args);
1.257     albertel 5330:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5331: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5332: 	    ($line,$err,$errmsg)=
                   5333: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5334: 					 $which,'answer',
                   5335: 					 { 'question'=>$question,
1.257     albertel 5336: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5337: 	    if ($err) { last; }
                   5338: 	}
                   5339:     }
                   5340:     if ($err) {
1.398     albertel 5341: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5342:     } else {
1.200     albertel 5343: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5344: 	&scantron_putfile($scanlines,$scan_data);
                   5345:     }
                   5346: }
                   5347: 
1.423     albertel 5348: =pod
                   5349: 
                   5350: =item reset_skipping_status
                   5351: 
1.424     albertel 5352:    Forgets the current set of remember skipped scanlines (and thus
                   5353:    reverts back to considering all lines in the
                   5354:    scantron_skipped_<filename> file)
                   5355: 
1.423     albertel 5356: =cut
                   5357: 
1.200     albertel 5358: sub reset_skipping_status {
                   5359:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5360:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5361:     &scantron_putfile(undef,$scan_data);
                   5362: }
                   5363: 
1.423     albertel 5364: =pod
                   5365: 
                   5366: =item start_skipping
                   5367: 
1.424     albertel 5368:    Marks a scanline to be skipped. 
                   5369: 
1.423     albertel 5370: =cut
                   5371: 
1.376     albertel 5372: sub start_skipping {
1.200     albertel 5373:     my ($scan_data,$i)=@_;
                   5374:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5375:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5376: 	$remembered{$i}=2;
                   5377:     } else {
                   5378: 	$remembered{$i}=1;
                   5379:     }
1.200     albertel 5380:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5381: }
                   5382: 
1.423     albertel 5383: =pod
                   5384: 
                   5385: =item should_be_skipped
                   5386: 
1.424     albertel 5387:    Checks whether a scanline should be skipped.
                   5388: 
1.423     albertel 5389: =cut
                   5390: 
1.200     albertel 5391: sub should_be_skipped {
1.376     albertel 5392:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5393:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5394: 	# not redoing old skips
1.376     albertel 5395: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5396: 	return 0;
                   5397:     }
                   5398:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5399: 
                   5400:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5401: 	return 0;
                   5402:     }
1.200     albertel 5403:     return 1;
                   5404: }
                   5405: 
1.423     albertel 5406: =pod
                   5407: 
                   5408: =item remember_current_skipped
                   5409: 
1.424     albertel 5410:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5411:    file and remembers them into scan_data for later use.
                   5412: 
1.423     albertel 5413: =cut
                   5414: 
1.200     albertel 5415: sub remember_current_skipped {
                   5416:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5417:     my %to_remember;
                   5418:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5419: 	if ($scanlines->{'skipped'}[$i]) {
                   5420: 	    $to_remember{$i}=1;
                   5421: 	}
                   5422:     }
1.376     albertel 5423: 
1.200     albertel 5424:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5425:     &scantron_putfile(undef,$scan_data);
                   5426: }
                   5427: 
1.423     albertel 5428: =pod
                   5429: 
                   5430: =item check_for_error
                   5431: 
1.424     albertel 5432:     Checks if there was an error when attempting to remove a specific
                   5433:     scantron_.. bubble sheet data file. Prints out an error if
                   5434:     something went wrong.
                   5435: 
1.423     albertel 5436: =cut
                   5437: 
1.200     albertel 5438: sub check_for_error {
                   5439:     my ($r,$result)=@_;
                   5440:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5441: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5442:     }
                   5443: }
1.157     albertel 5444: 
1.423     albertel 5445: =pod
                   5446: 
                   5447: =item scantron_warning_screen
                   5448: 
1.424     albertel 5449:    Interstitial screen to make sure the operator has selected the
                   5450:    correct options before we start the validation phase.
                   5451: 
1.423     albertel 5452: =cut
                   5453: 
1.203     albertel 5454: sub scantron_warning_screen {
                   5455:     my ($button_text)=@_;
1.257     albertel 5456:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5457:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5458:     my $CODElist;
1.284     albertel 5459:     if ($scantron_config{'CODElocation'} &&
                   5460: 	$scantron_config{'CODEstart'} &&
                   5461: 	$scantron_config{'CODElength'}) {
                   5462: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5463: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5464: 	$CODElist=
                   5465: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5466: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5467:     }
1.203     albertel 5468:     return (<<STUFF);
                   5469: <p>
1.398     albertel 5470: <span class="LC_warning">Please double check the information
                   5471:                  below before clicking on '$button_text'</span>
1.203     albertel 5472: </p>
                   5473: <table>
1.284     albertel 5474: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5475: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5476: $CODElist
1.203     albertel 5477: </table>
                   5478: <br />
                   5479: <p> If this information is correct, please click on '$button_text'.</p>
                   5480: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5481: 
                   5482: <br />
                   5483: STUFF
                   5484: }
                   5485: 
1.423     albertel 5486: =pod
                   5487: 
                   5488: =item scantron_do_warning
                   5489: 
1.424     albertel 5490:    Check if the operator has picked something for all required
                   5491:    fields. Error out if something is missing.
                   5492: 
1.423     albertel 5493: =cut
                   5494: 
1.203     albertel 5495: sub scantron_do_warning {
                   5496:     my ($r)=@_;
1.324     albertel 5497:     my ($symb)=&get_symb($r);
1.203     albertel 5498:     if (!$symb) {return '';}
1.324     albertel 5499:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5500:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5501:     if ( $env{'form.selectpage'} eq '' ||
                   5502: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5503: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5504: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5505: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5506: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5507: 	} 
1.257     albertel 5508: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5509: 	    $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
1.237     albertel 5510: 	} 
1.257     albertel 5511: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5512: 	    $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
1.237     albertel 5513: 	} 
                   5514:     } else {
1.265     www      5515: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5516: 	$r->print(<<STUFF);
1.203     albertel 5517: $warning
1.265     www      5518: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5519: <input type="hidden" name="command" value="scantron_validate" />
                   5520: STUFF
1.237     albertel 5521:     }
1.352     albertel 5522:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5523:     return '';
                   5524: }
                   5525: 
1.423     albertel 5526: =pod
                   5527: 
                   5528: =item scantron_form_start
                   5529: 
1.424     albertel 5530:     html hidden input for remembering all selected grading options
                   5531: 
1.423     albertel 5532: =cut
                   5533: 
1.203     albertel 5534: sub scantron_form_start {
                   5535:     my ($max_bubble)=@_;
                   5536:     my $result= <<SCANTRONFORM;
                   5537: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5538:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5539:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5540:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5541:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5542:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5543:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5544:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5545:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5546:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5547: SCANTRONFORM
                   5548:     return $result;
                   5549: }
                   5550: 
1.423     albertel 5551: =pod
                   5552: 
                   5553: =item scantron_validate_file
                   5554: 
1.424     albertel 5555:     Dispatch routine for doing validation of a bubble sheet data file.
                   5556: 
                   5557:     Also processes any necessary information resets that need to
                   5558:     occur before validation begins (ignore previous corrections,
                   5559:     restarting the skipped records processing)
                   5560: 
1.423     albertel 5561: =cut
                   5562: 
1.157     albertel 5563: sub scantron_validate_file {
                   5564:     my ($r) = @_;
1.324     albertel 5565:     my ($symb)=&get_symb($r);
1.157     albertel 5566:     if (!$symb) {return '';}
1.324     albertel 5567:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5568:     
                   5569:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5570:     # them when doing the corrections reset
1.257     albertel 5571:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5572: 	&reset_skipping_status();
                   5573:     }
1.257     albertel 5574:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5575: 	&remember_current_skipped();
1.257     albertel 5576: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5577:     }
                   5578: 
1.257     albertel 5579:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5580: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5581: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5582: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5583: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5584:     }
1.200     albertel 5585: 
1.257     albertel 5586:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5587: 	&scantron_process_corrections($r);
                   5588:     }
1.424     albertel 5589:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5590:     #get the student pick code ready
                   5591:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5592:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5593:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5594:     $r->print($result);
                   5595:     
1.334     albertel 5596:     my @validate_phases=( 'sequence',
                   5597: 			  'ID',
1.157     albertel 5598: 			  'CODE',
                   5599: 			  'doublebubble',
                   5600: 			  'missingbubbles');
1.257     albertel 5601:     if (!$env{'form.validatepass'}) {
                   5602: 	$env{'form.validatepass'} = 0;
1.157     albertel 5603:     }
1.257     albertel 5604:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5605: 
                   5606:     my $stop=0;
                   5607:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5608: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5609: 	$r->rflush();
                   5610: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5611: 	{
                   5612: 	    no strict 'refs';
                   5613: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5614: 	}
                   5615:     }
                   5616:     if (!$stop) {
1.203     albertel 5617: 	my $warning=&scantron_warning_screen('Start Grading');
                   5618: 	$r->print(<<STUFF);
                   5619: Validation process complete.<br />
                   5620: $warning
                   5621: <input type="submit" name="submit" value="Start Grading" />
                   5622: <input type="hidden" name="command" value="scantron_process" />
                   5623: STUFF
                   5624: 
1.157     albertel 5625:     } else {
                   5626: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5627: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5628:     }
                   5629:     if ($stop) {
1.334     albertel 5630: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5631: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5632: 	    $r->print(' this error <br />');
                   5633: 
                   5634: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5635: 	} else {
                   5636: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5637: 	    $r->print(' using corrected info <br />');
                   5638: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5639: 	    $r->print(" this scanline saving it for later.");
                   5640: 	}
1.157     albertel 5641:     }
1.352     albertel 5642:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5643:     return '';
                   5644: }
                   5645: 
1.423     albertel 5646: 
                   5647: =pod
                   5648: 
                   5649: =item scantron_remove_file
                   5650: 
1.424     albertel 5651:    Removes the requested bubble sheet data file, makes sure that
                   5652:    scantron_original_<filename> is never removed
                   5653: 
                   5654: 
1.423     albertel 5655: =cut
                   5656: 
1.200     albertel 5657: sub scantron_remove_file {
1.192     albertel 5658:     my ($which)=@_;
1.257     albertel 5659:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5660:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5661:     my $file='scantron_';
1.200     albertel 5662:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5663: 	$file.=$which.'_';
1.192     albertel 5664:     } else {
                   5665: 	return 'refused';
                   5666:     }
1.257     albertel 5667:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5668:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5669: }
                   5670: 
1.423     albertel 5671: 
                   5672: =pod
                   5673: 
                   5674: =item scantron_remove_scan_data
                   5675: 
1.424     albertel 5676:    Removes all scan_data correction for the requested bubble sheet
                   5677:    data file.  (In the case that both the are doing skipped records we need
                   5678:    to remember the old skipped lines for the time being so that element
                   5679:    persists for a while.)
                   5680: 
1.423     albertel 5681: =cut
                   5682: 
1.200     albertel 5683: sub scantron_remove_scan_data {
1.257     albertel 5684:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5685:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5686:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5687:     my @todelete;
1.257     albertel 5688:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5689:     foreach my $key (@keys) {
                   5690: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5691: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5692: 		$key=~/remember_skipping/) {
                   5693: 		next;
                   5694: 	    }
1.192     albertel 5695: 	    push(@todelete,$key);
                   5696: 	}
                   5697:     }
1.200     albertel 5698:     my $result;
1.192     albertel 5699:     if (@todelete) {
1.200     albertel 5700: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5701:     }
                   5702:     return $result;
                   5703: }
                   5704: 
1.423     albertel 5705: 
                   5706: =pod
                   5707: 
                   5708: =item scantron_getfile
                   5709: 
1.424     albertel 5710:     Fetches the requested bubble sheet data file (all 3 versions), and
                   5711:     the scan_data hash
                   5712:   
                   5713:   Arguments:
                   5714:     None
                   5715: 
                   5716:   Returns:
                   5717:     2 hash references
                   5718: 
                   5719:      - first one has 
                   5720:          orig      -
                   5721:          corrected -
                   5722:          skipped   -  each of which points to an array ref of the specified
                   5723:                       file broken up into individual lines
                   5724:          count     - number of scanlines
                   5725:  
                   5726:      - second is the scan_data hash possible keys are
1.425     albertel 5727:        ($number refers to scanline numbered $number and thus the key affects
                   5728:         only that scanline
                   5729:         $bubline refers to the specific bubble line element and the aspects
                   5730:         refers to that specific bubble line element)
                   5731: 
                   5732:        $number.user - username:domain to use
                   5733:        $number.CODE_ignore_dup 
                   5734:                     - ignore the duplicate CODE error 
                   5735:        $number.useCODE
                   5736:                     - use the CODE in the scanline as is
                   5737:        $number.no_bubble.$bubline
                   5738:                     - it is valid that there is no bubbled in bubble
                   5739:                       at $number $bubline
                   5740:        remember_skipping
                   5741:                     - a frozen hash containing keys of $number and values
                   5742:                       of either 
                   5743:                         1 - we are on a 'do skipped records pass' and plan
                   5744:                             on processing this line
                   5745:                         2 - we are on a 'do skipped records pass' and this
                   5746:                             scanline has been marked to skip yet again
1.424     albertel 5747: 
1.423     albertel 5748: =cut
                   5749: 
1.157     albertel 5750: sub scantron_getfile {
1.200     albertel 5751:     #FIXME really would prefer a scantron directory
1.257     albertel 5752:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5753:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5754:     my $lines;
                   5755:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5756: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5757:     my %scanlines;
                   5758:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5759:     my $temp=$scanlines{'orig'};
                   5760:     $scanlines{'count'}=$#$temp;
                   5761: 
                   5762:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5763: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5764:     if ($lines eq '-1') {
                   5765: 	$scanlines{'corrected'}=[];
                   5766:     } else {
                   5767: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5768:     }
                   5769:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5770: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5771:     if ($lines eq '-1') {
                   5772: 	$scanlines{'skipped'}=[];
                   5773:     } else {
                   5774: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5775:     }
1.175     albertel 5776:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5777:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5778:     my %scan_data = @tmp;
                   5779:     return (\%scanlines,\%scan_data);
                   5780: }
                   5781: 
1.423     albertel 5782: =pod
                   5783: 
                   5784: =item lonnet_putfile
                   5785: 
1.424     albertel 5786:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   5787: 
                   5788:  Arguments:
                   5789:    $contents - data to store
                   5790:    $filename - filename to store $contents into
                   5791: 
                   5792:  Returns:
                   5793:    result value from &Apache::lonnet::finishuserfileupload
                   5794: 
1.423     albertel 5795: =cut
                   5796: 
1.157     albertel 5797: sub lonnet_putfile {
                   5798:     my ($contents,$filename)=@_;
1.257     albertel 5799:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5800:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5801:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 5802:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 5803: 
                   5804: }
                   5805: 
1.423     albertel 5806: =pod
                   5807: 
                   5808: =item scantron_putfile
                   5809: 
1.424     albertel 5810:     Stores the current version of the bubble sheet data files, and the
                   5811:     scan_data hash. (Does not modify the original version only the
                   5812:     corrected and skipped versions.
                   5813: 
                   5814:  Arguments:
                   5815:     $scanlines - hash ref that looks like the first return value from
                   5816:                  &scantron_getfile()
                   5817:     $scan_data - hash ref that looks like the second return value from
                   5818:                  &scantron_getfile()
                   5819: 
1.423     albertel 5820: =cut
                   5821: 
1.157     albertel 5822: sub scantron_putfile {
                   5823:     my ($scanlines,$scan_data) = @_;
1.200     albertel 5824:     #FIXME really would prefer a scantron directory
1.257     albertel 5825:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5826:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 5827:     if ($scanlines) {
                   5828: 	my $prefix='scantron_';
1.157     albertel 5829: # no need to update orig, shouldn't change
                   5830: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 5831: #		    $env{'form.scantron_selectfile'});
1.200     albertel 5832: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   5833: 			$prefix.'corrected_'.
1.257     albertel 5834: 			$env{'form.scantron_selectfile'});
1.200     albertel 5835: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   5836: 			$prefix.'skipped_'.
1.257     albertel 5837: 			$env{'form.scantron_selectfile'});
1.200     albertel 5838:     }
1.175     albertel 5839:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 5840: }
                   5841: 
1.423     albertel 5842: =pod
                   5843: 
                   5844: =item scantron_get_line
                   5845: 
1.424     albertel 5846:    Returns the correct version of the scanline
                   5847: 
                   5848:  Arguments:
                   5849:     $scanlines - hash ref that looks like the first return value from
                   5850:                  &scantron_getfile()
                   5851:     $scan_data - hash ref that looks like the second return value from
                   5852:                  &scantron_getfile()
                   5853:     $i         - number of the requested line (starts at 0)
                   5854: 
                   5855:  Returns:
                   5856:    A scanline, (either the original or the corrected one if it
                   5857:    exists), or undef if the requested scanline should be
                   5858:    skipped. (Either because it's an skipped scanline, or it's an
                   5859:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   5860:    pass.
                   5861: 
1.423     albertel 5862: =cut
                   5863: 
1.157     albertel 5864: sub scantron_get_line {
1.200     albertel 5865:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 5866:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   5867:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 5868:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   5869:     return $scanlines->{'orig'}[$i]; 
                   5870: }
                   5871: 
1.423     albertel 5872: =pod
                   5873: 
                   5874: =item scantron_todo_count
                   5875: 
1.424     albertel 5876:     Counts the number of scanlines that need processing.
                   5877: 
                   5878:  Arguments:
                   5879:     $scanlines - hash ref that looks like the first return value from
                   5880:                  &scantron_getfile()
                   5881:     $scan_data - hash ref that looks like the second return value from
                   5882:                  &scantron_getfile()
                   5883: 
                   5884:  Returns:
                   5885:     $count - number of scanlines to process
                   5886: 
1.423     albertel 5887: =cut
                   5888: 
1.200     albertel 5889: sub get_todo_count {
                   5890:     my ($scanlines,$scan_data)=@_;
                   5891:     my $count=0;
                   5892:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5893: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   5894: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5895: 	$count++;
                   5896:     }
                   5897:     return $count;
                   5898: }
                   5899: 
1.423     albertel 5900: =pod
                   5901: 
                   5902: =item scantron_put_line
                   5903: 
1.424     albertel 5904:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   5905:     data file.
                   5906: 
                   5907:  Arguments:
                   5908:     $scanlines - hash ref that looks like the first return value from
                   5909:                  &scantron_getfile()
                   5910:     $scan_data - hash ref that looks like the second return value from
                   5911:                  &scantron_getfile()
                   5912:     $i         - line number to update
                   5913:     $newline   - contents of the updated scanline
                   5914:     $skip      - if true make the line for skipping and update the
                   5915:                  'skipped' file
                   5916: 
1.423     albertel 5917: =cut
                   5918: 
1.157     albertel 5919: sub scantron_put_line {
1.200     albertel 5920:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 5921:     if ($skip) {
                   5922: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 5923: 	&start_skipping($scan_data,$i);
1.157     albertel 5924: 	return;
                   5925:     }
                   5926:     $scanlines->{'corrected'}[$i]=$newline;
                   5927: }
                   5928: 
1.423     albertel 5929: =pod
                   5930: 
                   5931: =item scantron_clear_skip
                   5932: 
1.424     albertel 5933:    Remove a line from the 'skipped' file
                   5934: 
                   5935:  Arguments:
                   5936:     $scanlines - hash ref that looks like the first return value from
                   5937:                  &scantron_getfile()
                   5938:     $scan_data - hash ref that looks like the second return value from
                   5939:                  &scantron_getfile()
                   5940:     $i         - line number to update
                   5941: 
1.423     albertel 5942: =cut
                   5943: 
1.376     albertel 5944: sub scantron_clear_skip {
                   5945:     my ($scanlines,$scan_data,$i)=@_;
                   5946:     if (exists($scanlines->{'skipped'}[$i])) {
                   5947: 	undef($scanlines->{'skipped'}[$i]);
                   5948: 	return 1;
                   5949:     }
                   5950:     return 0;
                   5951: }
                   5952: 
1.423     albertel 5953: =pod
                   5954: 
                   5955: =item scantron_filter_not_exam
                   5956: 
1.424     albertel 5957:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   5958:    filter out resources that are not marked as 'exam' mode
                   5959: 
1.423     albertel 5960: =cut
                   5961: 
1.334     albertel 5962: sub scantron_filter_not_exam {
                   5963:     my ($curres)=@_;
                   5964:     
                   5965:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   5966: 	# if the user has asked to not have either hidden
                   5967: 	# or 'randomout' controlled resources to be graded
                   5968: 	# don't include them
                   5969: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5970: 	    && $curres->randomout) {
                   5971: 	    return 0;
                   5972: 	}
                   5973: 	return 1;
                   5974:     }
                   5975:     return 0;
                   5976: }
                   5977: 
1.423     albertel 5978: =pod
                   5979: 
                   5980: =item scantron_validate_sequence
                   5981: 
1.424     albertel 5982:     Validates the selected sequence, checking for resource that are
                   5983:     not set to exam mode.
                   5984: 
1.423     albertel 5985: =cut
                   5986: 
1.334     albertel 5987: sub scantron_validate_sequence {
                   5988:     my ($r,$currentphase) = @_;
                   5989: 
                   5990:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5991:     my (undef,undef,$sequence)=
                   5992: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   5993: 
                   5994:     my $map=$navmap->getResourceByUrl($sequence);
                   5995: 
                   5996:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   5997:                                     value="ignore" />');
                   5998:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   5999: 	my @resources=
                   6000: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6001: 	if (@resources) {
1.357     banghart 6002: 	    $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 6003: 	    return (1,$currentphase);
                   6004: 	}
                   6005:     }
                   6006: 
                   6007:     return (0,$currentphase+1);
                   6008: }
                   6009: 
1.423     albertel 6010: =pod
                   6011: 
                   6012: =item scantron_validate_ID
                   6013: 
1.424     albertel 6014:    Validates all scanlines in the selected file to not have any
                   6015:    invalid or underspecified student IDs
                   6016: 
1.423     albertel 6017: =cut
                   6018: 
1.157     albertel 6019: sub scantron_validate_ID {
                   6020:     my ($r,$currentphase) = @_;
                   6021:     
                   6022:     #get student info
                   6023:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6024:     my %idmap=&username_to_idmap($classlist);
                   6025: 
                   6026:     #get scantron line setup
1.257     albertel 6027:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6028:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6029: 
                   6030:     my %found=('ids'=>{},'usernames'=>{});
                   6031:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6032: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6033: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6034: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6035: 						 $scan_data);
                   6036: 	my $id=$$scan_record{'scantron.ID'};
                   6037: 	my $found;
                   6038: 	foreach my $checkid (keys(%idmap)) {
                   6039: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6040: 	}
                   6041: 	if ($found) {
                   6042: 	    my $username=$idmap{$found};
                   6043: 	    if ($found{'ids'}{$found}) {
                   6044: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6045: 					 $line,'duplicateID',$found);
1.194     albertel 6046: 		return(1,$currentphase);
1.157     albertel 6047: 	    } elsif ($found{'usernames'}{$username}) {
                   6048: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6049: 					 $line,'duplicateID',$username);
1.194     albertel 6050: 		return(1,$currentphase);
1.157     albertel 6051: 	    }
1.186     albertel 6052: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6053: 	    $found{'ids'}{$found}++;
                   6054: 	    $found{'usernames'}{$username}++;
                   6055: 	} else {
                   6056: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6057: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6058: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6059: 		    &scantron_get_correction($r,$i,$scan_record,
                   6060: 					     \%scantron_config,
                   6061: 					     $line,'duplicateID',$username);
1.194     albertel 6062: 		    return(1,$currentphase);
1.157     albertel 6063: 		} elsif (!defined($username)) {
                   6064: 		    &scantron_get_correction($r,$i,$scan_record,
                   6065: 					     \%scantron_config,
                   6066: 					     $line,'incorrectID');
1.194     albertel 6067: 		    return(1,$currentphase);
1.157     albertel 6068: 		}
                   6069: 		$found{'usernames'}{$username}++;
                   6070: 	    } else {
                   6071: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6072: 					 $line,'incorrectID');
1.194     albertel 6073: 		return(1,$currentphase);
1.157     albertel 6074: 	    }
                   6075: 	}
                   6076:     }
                   6077: 
                   6078:     return (0,$currentphase+1);
                   6079: }
                   6080: 
1.423     albertel 6081: =pod
                   6082: 
                   6083: =item scantron_get_correction
                   6084: 
1.424     albertel 6085:    Builds the interface screen to interact with the operator to fix a
                   6086:    specific error condition in a specific scanline
                   6087: 
                   6088:  Arguments:
                   6089:     $r           - Apache request object
                   6090:     $i           - number of the current scanline
                   6091:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6092:     $scan_config - hash ref as returned from &get_scantron_config()
                   6093:     $line        - full contents of the current scanline
                   6094:     $error       - error condition, valid values are
                   6095:                    'incorrectCODE', 'duplicateCODE',
                   6096:                    'doublebubble', 'missingbubble',
                   6097:                    'duplicateID', 'incorrectID'
                   6098:     $arg         - extra information needed
                   6099:        For errors:
                   6100:          - duplicateID   - paper number that this studentID was seen before on
                   6101:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6102:                            seen on before
                   6103:          - incorrectCODE - current incorrect CODE 
                   6104:          - doublebubble  - array ref of the bubble lines that have double
                   6105:                            bubble errors
                   6106:          - missingbubble - array ref of the bubble lines that have missing
                   6107:                            bubble errors
                   6108: 
1.423     albertel 6109: =cut
                   6110: 
1.157     albertel 6111: sub scantron_get_correction {
                   6112:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6113: 
                   6114: #FIXME in the case of a duplicated ID the previous line, probaly need
                   6115: #to show both the current line and the previous one and allow skipping
                   6116: #the previous one or the current one
                   6117: 
1.161     albertel 6118:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6119:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6120: 	$r->print(" for PaperID <tt>".
                   6121: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6122:     } else {
                   6123: 	$r->print(" in scanline $i <pre>".
                   6124: 		  $line."</pre> \n");
                   6125:     }
1.242     albertel 6126:     my $message="<p>The ID on the form is  <tt>".
                   6127: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6128: 	"The name on the paper is ".
                   6129: 	$$scan_record{'scantron.LastName'}.",".
                   6130: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6131: 
1.157     albertel 6132:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6133:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6134:     if ($error =~ /ID$/) {
1.186     albertel 6135: 	if ($error eq 'incorrectID') {
1.157     albertel 6136: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6137: 	} elsif ($error eq 'duplicateID') {
                   6138: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6139: 	}
1.242     albertel 6140: 	$r->print($message);
1.157     albertel 6141: 	$r->print("<p>How should I handle this? <br /> \n");
                   6142: 	$r->print("\n<ul><li> ");
                   6143: 	#FIXME it would be nice if this sent back the user ID and
                   6144: 	#could do partial userID matches
                   6145: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6146: 				       'scantron_username','scantron_domain'));
                   6147: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6148: 	$r->print("\n@".
1.257     albertel 6149: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6150: 
                   6151: 	$r->print('</li>');
1.186     albertel 6152:     } elsif ($error =~ /CODE$/) {
                   6153: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6154: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6155: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6156: 	    $r->print("</p><p>The encoded CODE has also been used by a previous paper ".join(', ',@{$arg}).", and CODEs are supposed to be unique</p>\n");
1.186     albertel 6157: 	}
1.224     albertel 6158: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6159: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6160: 	$r->print($message);
1.186     albertel 6161: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6162: 	$r->print("\n<br /> ");
1.194     albertel 6163: 	my $i=0;
1.273     albertel 6164: 	if ($error eq 'incorrectCODE' 
                   6165: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6166: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6167: 	    if ($closest > 0) {
                   6168: 		foreach my $testcode (@{$closest}) {
                   6169: 		    my $checked='';
1.401     albertel 6170: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6171: 		    $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked /> Use the similar CODE <b><tt>".$testcode."</tt></b> instead.</label><input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
                   6172: 		    $r->print("\n<br />");
                   6173: 		    $i++;
                   6174: 		}
1.194     albertel 6175: 	    }
                   6176: 	}
1.273     albertel 6177: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6178: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6179: 	    $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked /> Use the CODE <b><tt>".$$scan_record{'scantron.CODE'}."</tt></b> that is was on the paper, ignoring the error.</label>");
                   6180: 	    $r->print("\n<br />");
                   6181: 	}
1.194     albertel 6182: 
1.188     albertel 6183: 	$r->print(<<ENDSCRIPT);
                   6184: <script type="text/javascript">
                   6185: function change_radio(field) {
1.190     albertel 6186:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6187:     var i;
                   6188:     for (i=0;i<slct.length;i++) {
                   6189:         if (slct[i].value==field) { slct[i].checked=true; }
                   6190:     }
                   6191: }
                   6192: </script>
                   6193: ENDSCRIPT
1.187     albertel 6194: 	my $href="/adm/pickcode?".
1.359     www      6195: 	   "form=".&escape("scantronupload").
                   6196: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6197: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6198: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6199: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6200: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6201: 	    $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_found' /> <a target='_blank' href='$href'>Select</a> a CODE from the list of all CODEs and use it.</label> Selected CODE is <input readonly='true' type='text' size='8' name='scantron_CODE_selectedvalue' onfocus=\"javascript:change_radio('use_found')\" onchange=\"javascript:change_radio('use_found')\" />");
                   6202: 	    $r->print("\n<br />");
                   6203: 	}
1.272     albertel 6204: 	$r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_typed' /> Use </label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" /> as the CODE.");
1.187     albertel 6205: 	$r->print("\n<br /><br />");
1.157     albertel 6206:     } elsif ($error eq 'doublebubble') {
                   6207: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6208: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6209: 		  join(',',@{$arg}).'" />');
1.242     albertel 6210: 	$r->print($message);
1.157     albertel 6211: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6212: 	foreach my $question (@{$arg}) {
                   6213: 	    my $selected=$$scan_record{"scantron.$question.answer"};
1.422     foxr     6214: 	    &scantron_bubble_selector($r,$scan_config,$question,
                   6215: 				      split('',$selected));
1.157     albertel 6216: 	}
                   6217:     } elsif ($error eq 'missingbubble') {
                   6218: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6219: 	$r->print($message);
1.157     albertel 6220: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6221: 	$r->print("Some questions have no scanned bubbles\n");
                   6222: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6223: 		  join(',',@{$arg}).'" />');
                   6224: 	foreach my $question (@{$arg}) {
                   6225: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   6226: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   6227: 	}
                   6228:     } else {
                   6229: 	$r->print("\n<ul>");
                   6230:     }
                   6231:     $r->print("\n</li></ul>");
                   6232: 
                   6233: }
1.423     albertel 6234: 
                   6235: =pod
                   6236: 
                   6237: =item scantron_bubble_selector
                   6238:   
                   6239:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6240:    possibly showing the existing the selected bubbles if known
1.423     albertel 6241: 
                   6242:  Arguments:
                   6243:     $r           - Apache request object
                   6244:     $scan_config - hash from &get_scantron_config()
                   6245:     $quest       - number of the bubble line to make a corrector for
                   6246:     $selected    - array of letters of previously selected bubbles
                   6247:     $lines       - if present, number of bubble lines to show
                   6248: 
                   6249: =cut
                   6250: 
1.157     albertel 6251: sub scantron_bubble_selector {
1.422     foxr     6252:     my ($r,$scan_config,$quest,@selected, $lines)=@_;
1.157     albertel 6253:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6254: 
                   6255:     my $scmode=$$scan_config{'Qon'};
                   6256:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6257: 
1.422     foxr     6258: 
                   6259:     if (!defined($lines)) {
                   6260: 	$lines = 1;
                   6261:     }
                   6262:     my $total_lines = $lines*2;
1.157     albertel 6263:     my @alphabet=('A'..'Z');
1.422     foxr     6264:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6265: 
                   6266:     for (my $l = 0; $l < $lines; $l++) {
                   6267: 	if ($l != 0) {
                   6268: 	    $r->print('<tr>');
                   6269: 	}
                   6270: 
                   6271: 	# FIXME:  This loop probably has to be considerably more clever for
                   6272: 	#  multiline bubbles: User can multibubble by having bubbles in
                   6273: 	#  several lines.  User can skip lines legitimately etc. etc.
                   6274: 
                   6275: 	for (my $i=0;$i<$max;$i++) {
                   6276: 	    $r->print("\n".'<td align="center">');
                   6277: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6278: 		$r->print('X'); 
                   6279: 		shift(@selected) ;
                   6280: 	    } else { 
                   6281: 		$r->print('&nbsp;'); 
                   6282: 	    }
                   6283: 	    $r->print('</td>');
                   6284: 	    
                   6285: 	}
                   6286: 
                   6287: 	if ($l == 0) {
                   6288: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6289: 
                   6290: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6291: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6292: 	
                   6293: 	}
                   6294: 
                   6295: 	$r->print('</tr><tr>');
                   6296: 
                   6297: 	# FIXME: This may have to be a bit more clever for
                   6298: 	#        multiline questions (different values e.g..).
                   6299: 
                   6300: 	for (my $i=0;$i<$max;$i++) {
                   6301: 	    $r->print("\n".
                   6302: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6303: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6304: 	}
                   6305: 	$r->print('</tr>');
                   6306: 
                   6307: 	    
1.157     albertel 6308:     }
1.422     foxr     6309:     $r->print('</table>');
1.157     albertel 6310: }
                   6311: 
1.423     albertel 6312: =pod
                   6313: 
                   6314: =item num_matches
                   6315: 
1.424     albertel 6316:    Counts the number of characters that are the same between the two arguments.
                   6317: 
                   6318:  Arguments:
                   6319:    $orig - CODE from the scanline
                   6320:    $code - CODE to match against
                   6321: 
                   6322:  Returns:
                   6323:    $count - integer count of the number of same characters between the
                   6324:             two arguments
                   6325: 
1.423     albertel 6326: =cut
                   6327: 
1.194     albertel 6328: sub num_matches {
                   6329:     my ($orig,$code) = @_;
                   6330:     my @code=split(//,$code);
                   6331:     my @orig=split(//,$orig);
                   6332:     my $same=0;
                   6333:     for (my $i=0;$i<scalar(@code);$i++) {
                   6334: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6335:     }
                   6336:     return $same;
                   6337: }
                   6338: 
1.423     albertel 6339: =pod
                   6340: 
                   6341: =item scantron_get_closely_matching_CODEs
                   6342: 
1.424     albertel 6343:    Cycles through all CODEs and finds the set that has the greatest
                   6344:    number of same characters as the provided CODE
                   6345: 
                   6346:  Arguments:
                   6347:    $allcodes - hash ref returned by &get_codes()
                   6348:    $CODE     - CODE from the current scanline
                   6349: 
                   6350:  Returns:
                   6351:    2 element list
                   6352:     - first elements is number of how closely matching the best fit is 
                   6353:       (5 means best set has 5 matching characters)
                   6354:     - second element is an arrary ref containing the set of valid CODEs
                   6355:       that best fit the passed in CODE
                   6356: 
1.423     albertel 6357: =cut
                   6358: 
1.194     albertel 6359: sub scantron_get_closely_matching_CODEs {
                   6360:     my ($allcodes,$CODE)=@_;
                   6361:     my @CODEs;
                   6362:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6363: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6364:     }
                   6365: 
                   6366:     return ($#CODEs,$CODEs[-1]);
                   6367: }
                   6368: 
1.423     albertel 6369: =pod
                   6370: 
                   6371: =item get_codes
                   6372: 
1.424     albertel 6373:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6374:    set of remembered CODEs.
                   6375: 
                   6376:  Arguments:
                   6377:   $old_name - name of the set of remembered CODEs
                   6378:   $cdom     - domain of the course
                   6379:   $cnum     - internal course name
                   6380: 
                   6381:  Returns:
                   6382:   %allcodes - keys are the valid CODEs, values are all 1
                   6383: 
1.423     albertel 6384: =cut
                   6385: 
1.194     albertel 6386: sub get_codes {
1.280     foxr     6387:     my ($old_name, $cdom, $cnum) = @_;
                   6388:     if (!$old_name) {
                   6389: 	$old_name=$env{'form.scantron_CODElist'};
                   6390:     }
                   6391:     if (!$cdom) {
                   6392: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6393:     }
                   6394:     if (!$cnum) {
                   6395: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6396:     }
1.278     albertel 6397:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6398: 				    $cdom,$cnum);
                   6399:     my %allcodes;
                   6400:     if ($result{"type\0$old_name"} eq 'number') {
                   6401: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6402:     } else {
                   6403: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6404:     }
1.194     albertel 6405:     return %allcodes;
                   6406: }
                   6407: 
1.423     albertel 6408: =pod
                   6409: 
                   6410: =item scantron_validate_CODE
                   6411: 
1.424     albertel 6412:    Validates all scanlines in the selected file to not have any
                   6413:    invalid or underspecified CODEs and that none of the codes are
                   6414:    duplicated if this was requested.
                   6415: 
1.423     albertel 6416: =cut
                   6417: 
1.157     albertel 6418: sub scantron_validate_CODE {
                   6419:     my ($r,$currentphase) = @_;
1.257     albertel 6420:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6421:     if ($scantron_config{'CODElocation'} &&
                   6422: 	$scantron_config{'CODEstart'} &&
                   6423: 	$scantron_config{'CODElength'}) {
1.257     albertel 6424: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6425: 	    &FIXME_blow_up()
                   6426: 	}
                   6427:     } else {
                   6428: 	return (0,$currentphase+1);
                   6429:     }
                   6430:     
                   6431:     my %usedCODEs;
                   6432: 
1.194     albertel 6433:     my %allcodes=&get_codes();
1.186     albertel 6434: 
                   6435:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6436:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6437: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6438: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6439: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6440: 						 $scan_data);
                   6441: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6442: 	my $error=0;
1.224     albertel 6443: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6444: 	    &scantron_get_correction($r,$i,$scan_record,
                   6445: 				     \%scantron_config,
                   6446: 				     $line,'incorrectCODE',\%allcodes);
                   6447: 	    return(1,$currentphase);
                   6448: 	}
1.221     albertel 6449: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6450: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6451: 	    &scantron_get_correction($r,$i,$scan_record,
                   6452: 				     \%scantron_config,
1.194     albertel 6453: 				     $line,'incorrectCODE',\%allcodes);
                   6454: 	    return(1,$currentphase);
1.186     albertel 6455: 	}
1.214     albertel 6456: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6457: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6458: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6459: 	    &scantron_get_correction($r,$i,$scan_record,
                   6460: 				     \%scantron_config,
1.194     albertel 6461: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6462: 	    return(1,$currentphase);
1.186     albertel 6463: 	}
1.194     albertel 6464: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6465:     }
1.157     albertel 6466:     return (0,$currentphase+1);
                   6467: }
                   6468: 
1.423     albertel 6469: =pod
                   6470: 
                   6471: =item scantron_validate_doublebubble
                   6472: 
1.424     albertel 6473:    Validates all scanlines in the selected file to not have any
                   6474:    bubble lines with multiple bubbles marked.
                   6475: 
1.423     albertel 6476: =cut
                   6477: 
1.157     albertel 6478: sub scantron_validate_doublebubble {
                   6479:     my ($r,$currentphase) = @_;
                   6480:     #get student info
                   6481:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6482:     my %idmap=&username_to_idmap($classlist);
                   6483: 
                   6484:     #get scantron line setup
1.257     albertel 6485:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6486:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6487:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6488: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6489: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6490: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6491: 						 $scan_data);
                   6492: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6493: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6494: 				 'doublebubble',
                   6495: 				 $$scan_record{'scantron.doubleerror'});
                   6496:     	return (1,$currentphase);
                   6497:     }
                   6498:     return (0,$currentphase+1);
                   6499: }
                   6500: 
1.423     albertel 6501: =pod
                   6502: 
                   6503: =item scantron_get_maxbubble
                   6504: 
1.424     albertel 6505:    Returns the maximum number of bubble lines that are expected to
                   6506:    occur. Does this by walking the selected sequence rendering the
                   6507:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6508:    for what the current value of the problem counter is.
                   6509: 
                   6510:    Caches the result to $env{'form.scantron_maxbubble'}
                   6511: 
1.423     albertel 6512: =cut
                   6513: 
1.330     albertel 6514: sub scantron_get_maxbubble {    
1.435     foxr     6515: 
1.257     albertel 6516:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6517: 	$env{'form.scantron_maxbubble'}) {
                   6518: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6519:     }
1.330     albertel 6520: 
1.191     albertel 6521:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6522:     my (undef,undef,$sequence)=
1.257     albertel 6523: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6524: 
1.191     albertel 6525:     my $map=$navmap->getResourceByUrl($sequence);
                   6526:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6527: 
                   6528:     &Apache::lonxml::clear_problem_counter();
                   6529: 
1.435     foxr     6530:     my $uname       = $env{'form.student'};
                   6531:     my $udom        = $env{'form.userdom'};
                   6532:     my $cid         = $env{'request.course.id'};
                   6533:     my $total_lines = 0;
                   6534:     %bubble_lines_per_response = ();
                   6535: 
1.191     albertel 6536:     foreach my $resource (@resources) {
1.435     foxr     6537: 	my $symb = $resource->symb();
1.330     albertel 6538: 	my $result=&Apache::lonnet::ssi($resource->src(),
1.435     foxr     6539: 					('symb' => $resource->symb()),
                   6540: 					('grade_target' => 'analyze'),
                   6541: 					('grade_courseid' => $cid),
                   6542: 					('grade_domain' => $udom),
                   6543: 					('grade_username' => $uname));
1.436     albertel 6544: 	my (undef, $an) =
1.435     foxr     6545: 	    split(/_HASH_REF__/,$result, 2);
                   6546: 
                   6547: 	my %analysis = &Apache::lonnet::str2hash($an);
                   6548: 
                   6549: 
                   6550: 
                   6551: 	foreach my $part_id (@{$analysis{'parts'}}) {
                   6552: 	    my $bubble_lines = $analysis{"$part_id.bubble_lines"}[0];
                   6553: 	    if (!$bubble_lines) {
                   6554: 		$bubble_lines = 1;
                   6555: 	    }
                   6556: 	    $bubble_lines_per_response{"$symb.$part_id"} = $bubble_lines;
                   6557: 	    $total_lines = $total_lines + $bubble_lines;
                   6558: 	}
                   6559: 
1.191     albertel 6560:     }
                   6561:     &Apache::lonnet::delenv('scantron\.');
1.330     albertel 6562:     $env{'form.scantron_maxbubble'} =
1.435     foxr     6563: 	$total_lines;
1.257     albertel 6564:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6565: }
                   6566: 
1.423     albertel 6567: =pod
                   6568: 
                   6569: =item scantron_validate_missingbubbles
                   6570: 
1.424     albertel 6571:    Validates all scanlines in the selected file to not have any
                   6572:    bubble lines with missing bubbles that haven't been verified as missing.
                   6573: 
1.423     albertel 6574: =cut
                   6575: 
1.157     albertel 6576: sub scantron_validate_missingbubbles {
                   6577:     my ($r,$currentphase) = @_;
                   6578:     #get student info
                   6579:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6580:     my %idmap=&username_to_idmap($classlist);
                   6581: 
                   6582:     #get scantron line setup
1.257     albertel 6583:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6584:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6585:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6586:     if (!$max_bubble) { $max_bubble=2**31; }
                   6587:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6588: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6589: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6590: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6591: 						 $scan_data);
                   6592: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6593: 	my @to_correct;
                   6594: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6595: 	    if ($missing > $max_bubble) { next; }
                   6596: 	    push(@to_correct,$missing);
                   6597: 	}
                   6598: 	if (@to_correct) {
                   6599: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6600: 				     $line,'missingbubble',\@to_correct);
                   6601: 	    return (1,$currentphase);
                   6602: 	}
                   6603: 
                   6604:     }
                   6605:     return (0,$currentphase+1);
                   6606: }
                   6607: 
1.423     albertel 6608: =pod
                   6609: 
                   6610: =item scantron_process_students
                   6611: 
                   6612:    Routine that does the actual grading of the bubble sheet information.
                   6613: 
                   6614:    The parsed scanline hash is added to %env 
                   6615: 
                   6616:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6617:    foreach resource , with the form data of
                   6618: 
                   6619: 	'submitted'     =>'scantron' 
                   6620: 	'grade_target'  =>'grade',
                   6621: 	'grade_username'=> username of student
                   6622: 	'grade_domain'  => domain of student
                   6623: 	'grade_courseid'=> of course
                   6624: 	'grade_symb'    => symb of resource to grade
                   6625: 
                   6626:     This triggers a grading pass. The problem grading code takes care
                   6627:     of converting the bubbled letter information (now in %env) into a
                   6628:     valid submission.
                   6629: 
                   6630: =cut
                   6631: 
1.82      albertel 6632: sub scantron_process_students {
1.75      albertel 6633:     my ($r) = @_;
1.257     albertel 6634:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6635:     my ($symb)=&get_symb($r);
1.81      albertel 6636:     if (!$symb) {return '';}
1.324     albertel 6637:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6638: 
1.257     albertel 6639:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6640:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6641:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6642:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6643:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6644:     my $map=$navmap->getResourceByUrl($sequence);
                   6645:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6646: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6647:     my $result= <<SCANTRONFORM;
1.81      albertel 6648: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6649:   <input type="hidden" name="command" value="scantron_configphase" />
                   6650:   $default_form_data
                   6651: SCANTRONFORM
1.82      albertel 6652:     $r->print($result);
                   6653: 
                   6654:     my @delayqueue;
1.140     albertel 6655:     my %completedstudents;
                   6656:     
1.200     albertel 6657:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6658:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6659:  				    'Scantron Progress',$count,
1.195     albertel 6660: 				    'inline',undef,'scantronupload');
1.140     albertel 6661:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6662: 					  'Processing first student');
                   6663:     my $start=&Time::HiRes::time();
1.158     albertel 6664:     my $i=-1;
1.200     albertel 6665:     my ($uname,$udom,$started);
1.157     albertel 6666:     while ($i<$scanlines->{'count'}) {
                   6667:  	($uname,$udom)=('','');
                   6668:  	$i++;
1.200     albertel 6669:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6670:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 6671: 	if ($started) {
                   6672: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   6673: 						     'last student');
                   6674: 	}
                   6675: 	$started=1;
1.157     albertel 6676:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6677:  						 $scan_data);
                   6678:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   6679:  					      \%idmap,$i)) {
                   6680:   	    &scantron_add_delay(\@delayqueue,$line,
                   6681:  				'Unable to find a student that matches',1);
                   6682:  	    next;
                   6683:   	}
                   6684:  	if (exists $completedstudents{$uname}) {
                   6685:  	    &scantron_add_delay(\@delayqueue,$line,
                   6686:  				'Student '.$uname.' has multiple sheets',2);
                   6687:  	    next;
                   6688:  	}
                   6689:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 6690: 
                   6691: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 6692:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 6693: 
                   6694: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   6695: 	    &scantron_putfile($scanlines,$scan_data);
                   6696: 	}
1.161     albertel 6697: 	
                   6698: 	my $i=0;
1.83      albertel 6699: 	foreach my $resource (@resources) {
1.85      albertel 6700: 	    $i++;
1.193     albertel 6701: 	    my %form=('submitted'     =>'scantron',
                   6702: 		      'grade_target'  =>'grade',
                   6703: 		      'grade_username'=>$uname,
                   6704: 		      'grade_domain'  =>$udom,
1.257     albertel 6705: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 6706: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 6707: 	    if (exists($scan_record->{'scantron.CODE'})
                   6708: 		&& 
                   6709: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 6710: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 6711: 	    } else {
                   6712: 		$form{'CODE'}='';
1.193     albertel 6713: 	    }
                   6714: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 6715: 	    if ($result ne '') {
                   6716: 		&Apache::lonnet::logthis("scantron grading error -> $result");
1.257     albertel 6717: 		&Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
1.227     albertel 6718: 	    }
1.213     albertel 6719: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 6720: 	}
1.140     albertel 6721: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 6722: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 6723:     } continue {
1.330     albertel 6724: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 6725: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 6726:     }
1.140     albertel 6727:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 6728: #    my $lasttime = &Time::HiRes::time()-$start;
                   6729: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 6730: 
1.200     albertel 6731:     $r->print("</form>");
1.324     albertel 6732:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 6733:     return '';
1.75      albertel 6734: }
1.157     albertel 6735: 
1.423     albertel 6736: =pod
                   6737: 
                   6738: =item scantron_upload_scantron_data
                   6739: 
                   6740:     Creates the screen for adding a new bubble sheet data file to a course.
                   6741: 
                   6742: =cut
                   6743: 
1.157     albertel 6744: sub scantron_upload_scantron_data {
                   6745:     my ($r)=@_;
1.257     albertel 6746:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 6747:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 6748: 							  'domainid',
                   6749: 							  'coursename');
1.257     albertel 6750:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 6751: 						   'domainid');
1.324     albertel 6752:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 6753:     $r->print(<<UPLOAD);
                   6754: <script type="text/javascript" language="javascript">
                   6755:     function checkUpload(formname) {
                   6756: 	if (formname.upfile.value == "") {
                   6757: 	    alert("Please use the browse button to select a file from your local directory.");
                   6758: 	    return false;
                   6759: 	}
                   6760: 	formname.submit();
                   6761:     }
                   6762: </script>
                   6763: 
                   6764: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 6765: $default_form_data
1.181     albertel 6766: <table>
                   6767: <tr><td>$select_link </td></tr>
                   6768: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   6769: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   6770: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   6771: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   6772: </table>
1.157     albertel 6773: <input name='command' value='scantronupload_save' type='hidden' />
                   6774: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   6775: </form>
                   6776: UPLOAD
                   6777:     return '';
                   6778: }
                   6779: 
1.423     albertel 6780: =pod
                   6781: 
                   6782: =item scantron_upload_scantron_data_save
                   6783: 
                   6784:    Adds a provided bubble information data file to the course if user
                   6785:    has the correct privileges to do so.  
                   6786: 
                   6787: =cut
                   6788: 
1.157     albertel 6789: sub scantron_upload_scantron_data_save {
                   6790:     my($r)=@_;
1.324     albertel 6791:     my ($symb)=&get_symb($r,1);
1.182     albertel 6792:     my $doanotherupload=
                   6793: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   6794: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   6795: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   6796: 	'</form>'."\n";
1.257     albertel 6797:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 6798: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 6799: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 6800: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 6801: 	if ($symb) {
1.324     albertel 6802: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 6803: 	} else {
                   6804: 	    $r->print($doanotherupload);
                   6805: 	}
1.162     albertel 6806: 	return '';
                   6807:     }
1.257     albertel 6808:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       6809:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 6810:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 6811:     #FIXME
                   6812:     #copied from lonnet::userfileupload()
                   6813:     #make that function able to target a specified course
                   6814:     # Replace Windows backslashes by forward slashes
                   6815:     $fname=~s/\\/\//g;
                   6816:     # Get rid of everything but the actual filename
                   6817:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   6818:     # Replace spaces by underscores
                   6819:     $fname=~s/\s+/\_/g;
                   6820:     # Replace all other weird characters by nothing
                   6821:     $fname=~s/[^\w\.\-]//g;
                   6822:     # See if there is anything left
                   6823:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       6824:     my $uploadedfile=$fname;
1.157     albertel 6825:     $fname='scantron_orig_'.$fname;
1.257     albertel 6826:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 6827: 	$r->print("<span class=\"LC_error\">Error:</span> The file you attempted to upload, <tt>".&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</tt>, contained no information. Please check that you entered the correct filename.");
1.183     albertel 6828:     } else {
1.275     albertel 6829: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 6830: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 6831: 	    $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
1.210     albertel 6832: 	} else {
1.398     albertel 6833: 	    $r->print("<span class=\"LC_error\">Error:</span> An error (".$result.") occurred when attempting to upload the file, <tt>".&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</tt>");
1.183     albertel 6834: 	}
                   6835:     }
1.174     albertel 6836:     if ($symb) {
1.209     ng       6837: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 6838:     } else {
1.182     albertel 6839: 	$r->print($doanotherupload);
1.174     albertel 6840:     }
1.157     albertel 6841:     return '';
                   6842: }
                   6843: 
1.423     albertel 6844: =pod
                   6845: 
                   6846: =item valid_file
                   6847: 
1.424     albertel 6848:    Validates that the requested bubble data file exists in the course.
1.423     albertel 6849: 
                   6850: =cut
                   6851: 
1.202     albertel 6852: sub valid_file {
                   6853:     my ($requested_file)=@_;
                   6854:     foreach my $filename (sort(&scantron_filenames())) {
                   6855: 	if ($requested_file eq $filename) { return 1; }
                   6856:     }
                   6857:     return 0;
                   6858: }
                   6859: 
1.423     albertel 6860: =pod
                   6861: 
                   6862: =item scantron_download_scantron_data
                   6863: 
                   6864:    Shows a list of the three internal files (original, corrected,
                   6865:    skipped) for a specific bubble sheet data file that exists in the
                   6866:    course.
                   6867: 
                   6868: =cut
                   6869: 
1.202     albertel 6870: sub scantron_download_scantron_data {
                   6871:     my ($r)=@_;
1.324     albertel 6872:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 6873:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6874:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6875:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 6876:     if (! &valid_file($file)) {
                   6877: 	$r->print(<<ERROR);
                   6878: 	<p>
                   6879: 	    The requested file name was invalid.
                   6880:         </p>
                   6881: ERROR
1.324     albertel 6882: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 6883: 	return;
                   6884:     }
                   6885:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   6886:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   6887:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   6888:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   6889:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   6890:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   6891:     $r->print(<<DOWNLOAD);
                   6892:     <p>
                   6893: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   6894:     </p>
                   6895:     <p>
                   6896: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   6897:     </p>
                   6898:     <p>
                   6899: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   6900:     </p>
                   6901: DOWNLOAD
1.324     albertel 6902:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 6903:     return '';
                   6904: }
1.157     albertel 6905: 
1.423     albertel 6906: =pod
                   6907: 
                   6908: =back
                   6909: 
                   6910: =cut
                   6911: 
1.75      albertel 6912: #-------- end of section for handling grading scantron forms -------
                   6913: #
                   6914: #-------------------------------------------------------------------
                   6915: 
1.72      ng       6916: #-------------------------- Menu interface -------------------------
                   6917: #
                   6918: #--- Show a Grading Menu button - Calls the next routine ---
                   6919: sub show_grading_menu_form {
1.324     albertel 6920:     my ($symb)=@_;
1.125     ng       6921:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 6922: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 6923: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       6924: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   6925: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   6926: 	'</form>'."\n";
                   6927:     return $result;
                   6928: }
                   6929: 
1.77      ng       6930: # -- Retrieve choices for grading form
                   6931: sub savedState {
                   6932:     my %savedState = ();
1.257     albertel 6933:     if ($env{'form.saveState'}) {
                   6934: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       6935: 	    my ($key,$value) = split(/=/,$_,2);
                   6936: 	    $savedState{$key} = $value;
                   6937: 	}
                   6938:     }
                   6939:     return \%savedState;
                   6940: }
1.76      ng       6941: 
1.72      ng       6942: #--- Displays the main menu page -------
                   6943: sub gradingmenu {
                   6944:     my ($request) = @_;
1.324     albertel 6945:     my ($symb)=&get_symb($request);
1.72      ng       6946:     if (!$symb) {return '';}
1.76      ng       6947:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       6948: 
                   6949:     $request->print(<<GRADINGMENUJS);
                   6950: <script type="text/javascript" language="javascript">
1.116     ng       6951:     function checkChoice(formname,val,cmdx) {
                   6952: 	if (val <= 2) {
                   6953: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       6954: 	    var cmdsave = cmd;
1.116     ng       6955: 	} else {
                   6956: 	    cmd = cmdx;
1.118     ng       6957: 	    cmdsave = 'submission';
1.116     ng       6958: 	}
                   6959: 	formname.command.value = cmd;
1.118     ng       6960: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 6961: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       6962: 	if (val < 5) formname.submit();
                   6963: 	if (val == 5) {
1.72      ng       6964: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   6965: 	    formname.submit();
                   6966: 	}
1.238     albertel 6967: 	if (val < 7) formname.submit();
1.72      ng       6968:     }
                   6969: 
                   6970:     function checkReceiptNo(formname,nospace) {
                   6971: 	var receiptNo = formname.receipt.value;
                   6972: 	var checkOpt = false;
                   6973: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   6974: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   6975: 	if (checkOpt) {
                   6976: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   6977: 	    formname.receipt.value = "";
                   6978: 	    formname.receipt.focus();
                   6979: 	    return false;
                   6980: 	}
                   6981: 	return true;
                   6982:     }
                   6983: </script>
                   6984: GRADINGMENUJS
1.118     ng       6985:     &commonJSfunctions($request);
1.398     albertel 6986:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
1.324     albertel 6987:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       6988:     $result.=$table;
1.76      ng       6989:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       6990:     my $savedState = &savedState();
1.118     ng       6991:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       6992:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       6993:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       6994:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       6995: 
                   6996:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 6997: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       6998: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   6999: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       7000: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       7001: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       7002: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       7003: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7004: 
1.326     albertel 7005:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   7006: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
1.72      ng       7007: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       7008: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   7009: 
1.326     albertel 7010:     $result.='<table width="100%" border="0">';
1.116     ng       7011:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.429     banghart 7012: 	'&nbsp;'.&mt('Select Section').': <select name="section" multiple="multiple" size="3">'."\n";
1.116     ng       7013:     if (ref($sections)) {
1.155     albertel 7014: 	foreach (sort (@$sections)) {
                   7015: 	    $result.='<option value="'.$_.'" '.
1.401     albertel 7016: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
1.155     albertel 7017: 	}
1.116     ng       7018:     }
1.401     albertel 7019:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.116     ng       7020: 
1.401     albertel 7021:     $result.=&mt('Student Status').':'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
1.72      ng       7022: 
1.116     ng       7023:     $result.='</td></tr>';
                   7024: 
1.288     albertel 7025:     $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
1.118     ng       7026: 	'<input type="radio" name="radioChoice" value="submission" '.
1.401     albertel 7027: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 7028: 	'</label> <select name="submitonly">'.
1.145     albertel 7029: 	'<option value="yes" '.
1.401     albertel 7030: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
1.301     albertel 7031: 	'<option value="queued" '.
1.401     albertel 7032: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
1.145     albertel 7033: 	'<option value="graded" '.
1.401     albertel 7034: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 7035: 	'<option value="incorrect" '.
1.401     albertel 7036: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 7037: 	'<option value="all" '.
1.401     albertel 7038: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       7039: 
1.116     ng       7040:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.288     albertel 7041: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.401     albertel 7042: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7043: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       7044: 
1.118     ng       7045:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
1.288     albertel 7046: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.401     albertel 7047: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7048: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       7049: 
1.116     ng       7050:     $result.='<tr bgcolor="#ffffe6"><td><br />'.
1.126     ng       7051: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       7052: 	'</td></tr></table>'."\n";
                   7053: 
                   7054:     $result.='</td><td valign="top">';
                   7055: 
1.326     albertel 7056:     $result.='<table width="100%" border="0">';
1.116     ng       7057:     $result.='<tr bgcolor="#ffffe6"><td>'.
1.184     www      7058: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   7059: 	' '.&mt('scores from file').' </td></tr>'."\n";
1.72      ng       7060: 
1.404     www      7061:     $result.='<tr bgcolor="#ffffe6"><td>'.
                   7062:         '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
                   7063:         ' '.&mt('clicker file').' </td></tr>'."\n";
1.400     www      7064: 
1.75      albertel 7065:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.116     ng       7066: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
1.184     www      7067: 	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
1.75      albertel 7068: 
1.257     albertel 7069:     if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
1.72      ng       7070: 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.184     www      7071: 	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   7072: 	    ' '.&mt('receipt').': '.
1.257     albertel 7073: 	    &Apache::lonnet::recprefix($env{'request.course.id'}).
1.326     albertel 7074: 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
1.72      ng       7075: 	    '</td></tr>'."\n";
                   7076:     } 
1.238     albertel 7077:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7078: 	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   7079: 	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
1.279     albertel 7080:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7081: 	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   7082: 	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
1.44      ng       7083: 
1.401     albertel 7084:     $result.='</table>'."\n".
1.72      ng       7085: 	'</td></tr></table>'."\n".
1.401     albertel 7086: 	'</td></tr></table></form>'."\n";
1.44      ng       7087:     return $result;
1.2       albertel 7088: }
                   7089: 
1.285     albertel 7090: sub reset_perm {
                   7091:     undef(%perm);
                   7092: }
                   7093: 
                   7094: sub init_perm {
                   7095:     &reset_perm();
1.300     albertel 7096:     foreach my $test_perm ('vgr','mgr','opa') {
                   7097: 
                   7098: 	my $scope = $env{'request.course.id'};
                   7099: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7100: 
                   7101: 	    $scope .= '/'.$env{'request.course.sec'};
                   7102: 	    if ( $perm{$test_perm}=
                   7103: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7104: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7105: 	    } else {
                   7106: 		delete($perm{$test_perm});
                   7107: 	    }
1.285     albertel 7108: 	}
                   7109:     }
                   7110: }
                   7111: 
1.400     www      7112: sub gather_clicker_ids {
1.408     albertel 7113:     my %clicker_ids;
1.400     www      7114: 
                   7115:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7116: 
                   7117:     # Set up a couple variables.
1.407     albertel 7118:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7119:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      7120:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      7121: 
1.407     albertel 7122:     foreach my $student (keys(%$classlist)) {
1.438     www      7123:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 7124:         my $username = $classlist->{$student}->[$username_idx];
                   7125:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7126:         my $clickers =
1.408     albertel 7127: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7128:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7129:             $id=~s/^[\#0]+//;
1.421     www      7130:             $id=~s/[\-\:]//g;
1.407     albertel 7131:             if (exists($clicker_ids{$id})) {
1.408     albertel 7132: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7133:             } else {
1.408     albertel 7134: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7135:             }
                   7136:         }
                   7137:     }
1.407     albertel 7138:     return %clicker_ids;
1.400     www      7139: }
                   7140: 
1.402     www      7141: sub gather_adv_clicker_ids {
1.408     albertel 7142:     my %clicker_ids;
1.402     www      7143:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7144:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7145:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7146:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7147:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7148:             my ($puname,$pudom)=split(/\:/,$person);
                   7149:             my $clickers =
1.408     albertel 7150: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7151:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7152: 		$id=~s/^[\#0]+//;
1.421     www      7153:                 $id=~s/[\-\:]//g;
1.408     albertel 7154: 		if (exists($clicker_ids{$id})) {
                   7155: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7156: 		} else {
                   7157: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7158: 		}
1.405     www      7159:             }
1.402     www      7160:         }
                   7161:     }
1.407     albertel 7162:     return %clicker_ids;
1.402     www      7163: }
                   7164: 
1.413     www      7165: sub clicker_grading_parameters {
                   7166:     return ('gradingmechanism' => 'scalar',
                   7167:             'upfiletype' => 'scalar',
                   7168:             'specificid' => 'scalar',
                   7169:             'pcorrect' => 'scalar',
                   7170:             'pincorrect' => 'scalar');
                   7171: }
                   7172: 
1.400     www      7173: sub process_clicker {
                   7174:     my ($r)=@_;
                   7175:     my ($symb)=&get_symb($r);
                   7176:     if (!$symb) {return '';}
                   7177:     my $result=&checkforfile_js();
                   7178:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7179:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7180:     $result.=$table;
                   7181:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7182:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7183:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7184:         '.</b></td></tr>'."\n";
                   7185:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7186: # Attempt to restore parameters from last session, set defaults if not present
                   7187:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7188:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7189:                                                  \%Saveable_Parameters);
                   7190:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7191:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7192:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7193:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7194: 
                   7195:     my %checked;
                   7196:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7197:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7198:           $checked{$gradingmechanism}="checked='checked'";
                   7199:        }
                   7200:     }
                   7201: 
1.400     www      7202:     my $upload=&mt("Upload File");
                   7203:     my $type=&mt("Type");
1.402     www      7204:     my $attendance=&mt("Award points just for participation");
                   7205:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7206:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7207:     my $pcorrect=&mt("Percentage points for correct solution");
                   7208:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7209:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7210: 						   ('iclicker' => 'i>clicker',
                   7211:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7212:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7213:     $result.=<<ENDUPFORM;
1.402     www      7214: <script type="text/javascript">
                   7215: function sanitycheck() {
                   7216: // Accept only integer percentages
                   7217:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7218:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7219: // Find out grading choice
                   7220:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7221:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7222:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7223:       }
                   7224:    }
                   7225: // By default, new choice equals user selection
                   7226:    newgradingchoice=gradingchoice;
                   7227: // Not good to give more points for false answers than correct ones
                   7228:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7229:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7230:    }
                   7231: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7232:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7233:       document.forms.gradesupload.pcorrect.value=100;
                   7234:       document.forms.gradesupload.pincorrect.value=100;
                   7235:    }
                   7236: // If the values are different, cannot be attendance only
                   7237:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7238:        (gradingchoice=='attendance')) {
                   7239:        newgradingchoice='personnel';
                   7240:    }
                   7241: // Change grading choice to new one
                   7242:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7243:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7244:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7245:       } else {
                   7246:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7247:       }
                   7248:    }
                   7249: // Remember the old state
                   7250:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7251: }
                   7252: </script>
1.400     www      7253: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7254: <input type="hidden" name="symb" value="$symb" />
                   7255: <input type="hidden" name="command" value="processclickerfile" />
                   7256: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7257: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7258: <input type="file" name="upfile" size="50" />
                   7259: <br /><label>$type: $selectform</label>
1.413     www      7260: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
                   7261: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
                   7262: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
1.414     www      7263: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7264: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7265: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7266: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7267: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7268: </form>
                   7269: ENDUPFORM
                   7270:     $result.='</td></tr></table>'."\n".
                   7271:              '</td></tr></table><br /><br />'."\n";
                   7272:     $result.=&show_grading_menu_form($symb);
                   7273:     return $result;
                   7274: }
                   7275: 
                   7276: sub process_clicker_file {
                   7277:     my ($r)=@_;
                   7278:     my ($symb)=&get_symb($r);
                   7279:     if (!$symb) {return '';}
1.413     www      7280: 
                   7281:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7282:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7283:                                               \%Saveable_Parameters);
                   7284: 
1.400     www      7285:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7286:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7287: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7288: 	return $result.&show_grading_menu_form($symb);
1.404     www      7289:     }
1.407     albertel 7290:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7291:     my %correct_ids;
1.404     www      7292:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7293: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7294:     }
                   7295:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7296: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7297: 	   $correct_id=~tr/a-z/A-Z/;
                   7298: 	   $correct_id=~s/\s//gs;
                   7299: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7300:            $correct_id=~s/[\-\:]//g;
1.414     www      7301:            if ($correct_id) {
                   7302: 	      $correct_ids{$correct_id}='specified';
                   7303:            }
                   7304:         }
1.400     www      7305:     }
1.404     www      7306:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7307: 	$result.=&mt('Score based on attendance only');
1.404     www      7308:     } else {
1.408     albertel 7309: 	my $number=0;
1.411     www      7310: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7311: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7312: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7313: 	    if ($correct_ids{$id} eq 'specified') {
                   7314: 		$result.=&mt('specified');
                   7315: 	    } else {
                   7316: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7317: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7318: 	    }
                   7319: 	    $number++;
                   7320: 	}
1.411     www      7321:         $result.="</p>\n";
1.408     albertel 7322: 	if ($number==0) {
                   7323: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7324: 	    return $result.&show_grading_menu_form($symb);
                   7325: 	}
1.404     www      7326:     }
1.405     www      7327:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7328:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7329: 		     '<span class="LC_error">',
                   7330: 		     '</span>',
                   7331: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7332:         return $result.&show_grading_menu_form($symb);
                   7333:     }
1.410     www      7334: 
                   7335: # Were able to get all the info needed, now analyze the file
                   7336: 
1.411     www      7337:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7338:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7339:     my $heading=&mt('Scanning clicker file');
                   7340:     $result.=(<<ENDHEADER);
                   7341: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7342: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7343: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7344: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7345: <input type="hidden" name="symb" value="$symb" />
                   7346: <input type="hidden" name="command" value="assignclickergrades" />
                   7347: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7348: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7349: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7350: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7351: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7352: ENDHEADER
1.408     albertel 7353:     my %responses;
                   7354:     my @questiontitles;
1.405     www      7355:     my $errormsg='';
                   7356:     my $number=0;
                   7357:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7358: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7359:     }
1.419     www      7360:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7361:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7362:     }
1.411     www      7363:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7364:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   7365:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7366:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7367:              '<br />';
1.414     www      7368: # Remember Question Titles
                   7369: # FIXME: Possibly need delimiter other than ":"
                   7370:     for (my $i=0;$i<$number;$i++) {
                   7371:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7372:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7373:     }
1.411     www      7374:     my $correct_count=0;
                   7375:     my $student_count=0;
                   7376:     my $unknown_count=0;
1.414     www      7377: # Match answers with usernames
                   7378: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7379:     foreach my $id (keys(%responses)) {
1.410     www      7380:        if ($correct_ids{$id}) {
1.414     www      7381:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7382:           $correct_count++;
1.410     www      7383:        } elsif ($clicker_ids{$id}) {
1.437     www      7384:           if ($clicker_ids{$id}=~/\,/) {
                   7385: # More than one user with the same clicker!
                   7386:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   7387:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7388:                            "<select name='multi".$id."'>";
                   7389:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   7390:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   7391:              }
                   7392:              $result.='</select>';
                   7393:              $unknown_count++;
                   7394:           } else {
                   7395: # Good: found one and only one user with the right clicker
                   7396:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   7397:              $student_count++;
                   7398:           }
1.410     www      7399:        } else {
1.411     www      7400:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7401:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7402:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7403:                    "\n".&mt("Domain").": ".
                   7404:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7405:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7406:           $unknown_count++;
1.410     www      7407:        }
1.405     www      7408:     }
1.412     www      7409:     $result.='<hr />'.
                   7410:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7411:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7412:        if ($correct_count==0) {
                   7413:           $errormsg.="Found no correct answers answers for grading!";
                   7414:        } elsif ($correct_count>1) {
1.414     www      7415:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7416:        }
                   7417:     }
1.428     www      7418:     if ($number<1) {
                   7419:        $errormsg.="Found no questions.";
                   7420:     }
1.412     www      7421:     if ($errormsg) {
                   7422:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7423:     } else {
                   7424:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7425:     }
                   7426:     $result.='</form></td></tr></table>'."\n".
1.410     www      7427:              '</td></tr></table><br /><br />'."\n";
1.404     www      7428:     return $result.&show_grading_menu_form($symb);
1.400     www      7429: }
                   7430: 
1.405     www      7431: sub iclicker_eval {
1.406     www      7432:     my ($questiontitles,$responses)=@_;
1.405     www      7433:     my $number=0;
                   7434:     my $errormsg='';
                   7435:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7436:         my %components=&Apache::loncommon::record_sep($line);
                   7437:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7438: 	if ($entries[0] eq 'Question') {
                   7439: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7440: 		$$questiontitles[$number]=$entries[$i];
                   7441: 		$number++;
                   7442: 	    }
                   7443: 	}
                   7444: 	if ($entries[0]=~/^\#/) {
                   7445: 	    my $id=$entries[0];
                   7446: 	    my @idresponses;
                   7447: 	    $id=~s/^[\#0]+//;
                   7448: 	    for (my $i=0;$i<$number;$i++) {
                   7449: 		my $idx=3+$i*6;
                   7450: 		push(@idresponses,$entries[$idx]);
                   7451: 	    }
                   7452: 	    $$responses{$id}=join(',',@idresponses);
                   7453: 	}
1.405     www      7454:     }
                   7455:     return ($errormsg,$number);
                   7456: }
                   7457: 
1.419     www      7458: sub interwrite_eval {
                   7459:     my ($questiontitles,$responses)=@_;
                   7460:     my $number=0;
                   7461:     my $errormsg='';
1.420     www      7462:     my $skipline=1;
                   7463:     my $questionnumber=0;
                   7464:     my %idresponses=();
1.419     www      7465:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   7466:         my %components=&Apache::loncommon::record_sep($line);
                   7467:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      7468:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   7469:         if ($entries[1] eq 'Response') { $skipline=1; }
                   7470:         next if $skipline;
                   7471:         if ($entries[0]!=$questionnumber) {
                   7472:            $questionnumber=$entries[0];
                   7473:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   7474:            $number++;
1.419     www      7475:         }
1.420     www      7476:         my $id=$entries[4];
                   7477:         $id=~s/^[\#0]+//;
1.421     www      7478:         $id=~s/^v\d*\://i;
                   7479:         $id=~s/[\-\:]//g;
1.420     www      7480:         $idresponses{$id}[$number]=$entries[6];
                   7481:     }
                   7482:     foreach my $id (keys %idresponses) {
                   7483:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   7484:        $$responses{$id}=~s/^\s*\,//;
1.419     www      7485:     }
                   7486:     return ($errormsg,$number);
                   7487: }
                   7488: 
1.414     www      7489: sub assign_clicker_grades {
                   7490:     my ($r)=@_;
                   7491:     my ($symb)=&get_symb($r);
                   7492:     if (!$symb) {return '';}
1.416     www      7493: # See which part we are saving to
                   7494:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   7495: # FIXME: This should probably look for the first handgradeable part
                   7496:     my $part=$$partlist[0];
                   7497: # Start screen output
1.414     www      7498:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      7499: 
1.414     www      7500:     my $heading=&mt('Assigning grades based on clicker file');
                   7501:     $result.=(<<ENDHEADER);
                   7502: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7503: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7504: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7505: ENDHEADER
                   7506: # Get correct result
                   7507: # FIXME: Possibly need delimiter other than ":"
                   7508:     my @correct=();
1.415     www      7509:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   7510:     my $number=$env{'form.number'};
                   7511:     if ($gradingmechanism ne 'attendance') {
1.414     www      7512:        foreach my $key (keys(%env)) {
                   7513:           if ($key=~/^form\.correct\:/) {
                   7514:              my @input=split(/\,/,$env{$key});
                   7515:              for (my $i=0;$i<=$#input;$i++) {
                   7516:                  if (($correct[$i]) && ($input[$i]) &&
                   7517:                      ($correct[$i] ne $input[$i])) {
                   7518:                     $result.='<br /><span class="LC_warning">'.
                   7519:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   7520:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   7521:                  } elsif ($input[$i]) {
                   7522:                     $correct[$i]=$input[$i];
                   7523:                  }
                   7524:              }
                   7525:           }
                   7526:        }
1.415     www      7527:        for (my $i=0;$i<$number;$i++) {
1.414     www      7528:           if (!$correct[$i]) {
                   7529:              $result.='<br /><span class="LC_error">'.
                   7530:                       &mt('No correct result given for question "[_1]"!',
                   7531:                           $env{'form.question:'.$i}).'</span>';
                   7532:           }
                   7533:        }
                   7534:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   7535:     }
                   7536: # Start grading
1.415     www      7537:     my $pcorrect=$env{'form.pcorrect'};
                   7538:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      7539:     my $storecount=0;
1.415     www      7540:     foreach my $key (keys(%env)) {
1.420     www      7541:        my $user='';
1.415     www      7542:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      7543:           $user=$1;
                   7544:        }
                   7545:        if ($key=~/^form\.unknown\:(.*)$/) {
                   7546:           my $id=$1;
                   7547:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   7548:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      7549:           } elsif ($env{'form.multi'.$id}) {
                   7550:              $user=$env{'form.multi'.$id};
1.420     www      7551:           }
                   7552:        }
                   7553:        if ($user) { 
1.415     www      7554:           my @answer=split(/\,/,$env{$key});
                   7555:           my $sum=0;
                   7556:           for (my $i=0;$i<$number;$i++) {
                   7557:              if ($answer[$i]) {
                   7558:                 if ($gradingmechanism eq 'attendance') {
                   7559:                    $sum+=$pcorrect;
                   7560:                 } else {
                   7561:                    if ($answer[$i] eq $correct[$i]) {
                   7562:                       $sum+=$pcorrect;
                   7563:                    } else {
                   7564:                       $sum+=$pincorrect;
                   7565:                    }
                   7566:                 }
                   7567:              }
                   7568:           }
1.416     www      7569:           my $ave=$sum/(100*$number);
                   7570: # Store
                   7571:           my ($username,$domain)=split(/\:/,$user);
                   7572:           my %grades=();
                   7573:           $grades{"resource.$part.solved"}='correct_by_override';
                   7574:           $grades{"resource.$part.awarded"}=$ave;
                   7575:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   7576:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   7577:                                                  $env{'request.course.id'},
                   7578:                                                  $domain,$username);
                   7579:           if ($returncode ne 'ok') {
                   7580:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   7581:           } else {
                   7582:              $storecount++;
                   7583:           }
1.415     www      7584:        }
                   7585:     }
                   7586: # We are done
1.416     www      7587:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   7588:              '</td></tr></table>'."\n".
1.414     www      7589:              '</td></tr></table><br /><br />'."\n";
                   7590:     return $result.&show_grading_menu_form($symb);
                   7591: }
                   7592: 
1.1       albertel 7593: sub handler {
1.41      ng       7594:     my $request=$_[0];
1.102     albertel 7595: 
1.434     albertel 7596:     &reset_caches();
1.257     albertel 7597:     if ($env{'browser.mathml'}) {
1.141     www      7598: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       7599:     } else {
1.141     www      7600: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       7601:     }
                   7602:     $request->send_http_header;
1.44      ng       7603:     return '' if $request->header_only;
1.41      ng       7604:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 7605:     my $symb=&get_symb($request,1);
1.160     albertel 7606:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   7607:     my $command=$commands[0];
                   7608:     if ($#commands > 0) {
                   7609: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   7610:     }
1.353     albertel 7611:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 7612:     if ($symb eq '' && $command eq '') {
1.257     albertel 7613: 	if ($env{'user.adv'}) {
                   7614: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   7615: 		($env{'form.codethree'})) {
                   7616: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   7617: 		    $env{'form.codethree'};
1.41      ng       7618: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   7619: 		    &Apache::lonnet::checkin($token);
                   7620: 		if ($tsymb) {
1.137     albertel 7621: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       7622: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 7623: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   7624: 					  ('grade_username' => $tuname,
                   7625: 					   'grade_domain' => $tudom,
                   7626: 					   'grade_courseid' => $tcrsid,
                   7627: 					   'grade_symb' => $tsymb)));
1.41      ng       7628: 		    } else {
1.45      ng       7629: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 7630: 		    }
1.41      ng       7631: 		} else {
1.45      ng       7632: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       7633: 		}
1.14      www      7634: 	    } else {
1.41      ng       7635: 		$request->print(&Apache::lonxml::tokeninputfield());
                   7636: 	    }
                   7637: 	}
                   7638:     } else {
1.285     albertel 7639: 	&init_perm();
1.104     albertel 7640: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 7641: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 7642: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       7643: 	    &pickStudentPage($request);
1.103     albertel 7644: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       7645: 	    &displayPage($request);
1.104     albertel 7646: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       7647: 	    &updateGradeByPage($request);
1.104     albertel 7648: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       7649: 	    &processGroup($request);
1.104     albertel 7650: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.41      ng       7651: 	    $request->print(&gradingmenu($request));
1.104     albertel 7652: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       7653: 	    $request->print(&viewgrades($request));
1.104     albertel 7654: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       7655: 	    $request->print(&processHandGrade($request));
1.106     albertel 7656: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       7657: 	    $request->print(&editgrades($request));
1.106     albertel 7658: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       7659: 	    $request->print(&verifyreceipt($request));
1.400     www      7660:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   7661:             $request->print(&process_clicker($request));
                   7662:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   7663:             $request->print(&process_clicker_file($request));
1.414     www      7664:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   7665:             $request->print(&assign_clicker_grades($request));
1.106     albertel 7666: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       7667: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 7668: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       7669: 	    $request->print(&csvupload($request));
1.106     albertel 7670: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       7671: 	    $request->print(&csvuploadmap($request));
1.246     albertel 7672: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 7673: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 7674: 		$request->print(&csvuploadoptions($request));
1.41      ng       7675: 	    } else {
1.257     albertel 7676: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   7677: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       7678: 		} else {
1.257     albertel 7679: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       7680: 		}
                   7681: 		$request->print(&csvuploadmap($request));
                   7682: 	    }
1.246     albertel 7683: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   7684: 	    $request->print(&csvuploadassign($request));
1.106     albertel 7685: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 7686: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 7687:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   7688:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 7689: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   7690: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 7691: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 7692: 	    $request->print(&scantron_process_students($request));
1.157     albertel 7693:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 7694:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   7695: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 7696:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 7697:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 7698:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   7699: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 7700:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 7701:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 7702: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 7703:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 7704: 	} elsif ($command) {
1.157     albertel 7705: 	    $request->print("Access Denied ($command)");
1.26      albertel 7706: 	}
1.2       albertel 7707:     }
1.353     albertel 7708:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 7709:     &reset_caches();
1.44      ng       7710:     return '';
                   7711: }
                   7712: 
1.1       albertel 7713: 1;
                   7714: 
1.13      albertel 7715: __END__;

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