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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.428.2.1! albertel    4: # $Id: grades.pm,v 1.428 2007/08/11 13:32:23 www 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.428.2.1! albertel   48: my %perm;
1.1       albertel   49: 
1.68      ng         50: # ----- These first few routines are general use routines.----
1.44      ng         51: #
1.146     albertel   52: # --- Retrieve the parts from the metadata file.---
1.44      ng         53: sub getpartlist {
1.324     albertel   54:     my ($symb) = @_;
                     55:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.146     albertel   56:     my $partorder = &Apache::lonnet::metadata($url, 'partorder');
                     57:     my @parts;
                     58:     if ($partorder) {
                     59: 	for my $part (split (/,/,$partorder)) {
                     60: 	    if (!&Apache::loncommon::check_if_partid_hidden($part,$symb)) {
                     61: 		push(@parts, $part);
                     62: 	    }
                     63: 	}	    
                     64:     } else {
                     65: 	my $metadata = &Apache::lonnet::metadata($url, 'packages');
                     66: 	foreach (split(/\,/,$metadata)) {
                     67: 	    if ($_ =~ /^part_(.*)$/) {
                     68: 		if (!&Apache::loncommon::check_if_partid_hidden($1,$symb)) {
                     69: 		    push(@parts, $1);
                     70: 		}
                     71: 	    }
1.41      ng         72: 	}
1.16      albertel   73:     }
1.146     albertel   74:     my @stores;
                     75:     foreach my $part (@parts) {
                     76: 	my (@metakeys) = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                     77: 	foreach my $key (@metakeys) {
                     78: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                     79: 	}
                     80:     }
                     81:     return @stores;
1.2       albertel   82: }
                     83: 
1.44      ng         84: # --- Get the symbolic name of a problem and the url
1.324     albertel   85: sub get_symb {
1.173     albertel   86:     my ($request,$silent) = @_;
1.257     albertel   87:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                     88:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel   89:     if ($symb eq '') { 
                     90: 	if (!$silent) {
                     91: 	    $request->print("Unable to handle ambiguous references:$url:.");
                     92: 	    return ();
                     93: 	}
                     94:     }
1.418     albertel   95:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel   96:     return ($symb);
1.32      ng         97: }
                     98: 
1.129     ng         99: #--- Format fullname, username:domain if different for display
                    100: #--- Use anywhere where the student names are listed
                    101: sub nameUserString {
                    102:     my ($type,$fullname,$uname,$udom) = @_;
                    103:     if ($type eq 'header') {
1.398     albertel  104: 	return '<b>&nbsp;Fullname&nbsp;</b><span class="LC_internal_info">(Username)</span>';
1.129     ng        105:     } else {
1.398     albertel  106: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    107: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        108:     }
                    109: }
                    110: 
1.44      ng        111: #--- Get the partlist and the response type for a given problem. ---
                    112: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        113: sub response_type {
1.324     albertel  114:     my ($symb) = shift;
1.377     albertel  115: 
                    116:     my $navmap = Apache::lonnavmaps::navmap->new();
                    117:     my $res = $navmap->getBySymb($symb);
                    118:     my $partlist = $res->parts();
1.392     albertel  119:     my %vPart = 
                    120: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  121:     my (%response_types,%handgrade);
                    122:     foreach my $part (@{ $partlist }) {
1.392     albertel  123: 	next if (%vPart && !exists($vPart{$part}));
                    124: 
1.377     albertel  125: 	my @types = $res->responseType($part);
                    126: 	my @ids = $res->responseIds($part);
                    127: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    128: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    129: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    130: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    131: 				     '.handgrade',$symb);
1.41      ng        132: 	}
                    133:     }
1.377     albertel  134:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        135: }
                    136: 
1.375     albertel  137: sub flatten_responseType {
                    138:     my ($responseType) = @_;
                    139:     my @part_response_id =
                    140: 	map { 
                    141: 	    my $part = $_;
                    142: 	    map {
                    143: 		[$part,$_]
                    144: 		} sort(keys(%{ $responseType->{$part} }));
                    145: 	} sort(keys(%$responseType));
                    146:     return @part_response_id;
                    147: }
                    148: 
1.207     albertel  149: sub get_display_part {
1.324     albertel  150:     my ($partID,$symb)=@_;
1.207     albertel  151:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    152:     if (defined($display) and $display ne '') {
1.398     albertel  153: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  154:     } else {
                    155: 	$display=$partID;
                    156:     }
                    157:     return $display;
                    158: }
1.269     raeburn   159: 
1.118     ng        160: #--- Show resource title
                    161: #--- and parts and response type
                    162: sub showResourceInfo {
1.324     albertel  163:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  164:     my $col=3;
                    165:     if ($checkboxes) { $col=4; }
1.398     albertel  166:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    167:     $result .='<table border="0">';
1.324     albertel  168:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        169:     my %resptype = ();
1.122     ng        170:     my $hdgrade='no';
1.154     albertel  171:     my %partsseen;
1.375     albertel  172:     foreach my $partID (sort keys(%$responseType)) {
                    173: 	foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
                    174: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    175: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    176: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    177: 	    $result.='<tr>';
                    178: 	    if ($checkboxes) {
                    179: 		if (exists($partsseen{$partID})) {
                    180: 		    $result.="<td>&nbsp;</td>";
                    181: 		} else {
1.401     albertel  182: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  183: 		}
                    184: 		$partsseen{$partID}=1;
1.154     albertel  185: 	    }
1.375     albertel  186: 	    my $display_part=&get_display_part($partID,$symb);
1.398     albertel  187: 	    $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
                    188: 		$resID.'</span></td>'.
1.375     albertel  189: 		'<td><b>Type: </b>'.$responsetype.'</td></tr>';
                    190: #	    '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
1.154     albertel  191: 	}
1.118     ng        192:     }
                    193:     $result.='</table>'."\n";
1.147     albertel  194:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        195: }
                    196: 
1.428.2.1! albertel  197: sub reset_caches {
        !           198:     &reset_analyze_cache();
        !           199:     &reset_perm();
        !           200: }
1.148     albertel  201: 
1.428.2.1! albertel  202: {
        !           203:     my %analyze_cache;
        !           204: 
        !           205:     sub reset_analyze_cache {
        !           206: 	undef(%analyze_cache);
        !           207:     }
        !           208: 
        !           209:     sub get_analyze {
        !           210: 	my ($symb,$uname,$udom)=@_;
        !           211: 	my $key = "$symb\0$uname\0$udom";
        !           212: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
        !           213: 
        !           214: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
        !           215: 	$url=&Apache::lonnet::clutter($url);
        !           216: 	my $subresult=&Apache::lonnet::ssi($url,
        !           217: 					   ('grade_target' => 'analyze'),
        !           218: 					   ('grade_domain' => $udom),
        !           219: 					   ('grade_symb' => $symb),
        !           220: 					   ('grade_courseid' => 
        !           221: 					    $env{'request.course.id'}),
        !           222: 					   ('grade_username' => $uname));
        !           223: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
        !           224: 	my %analyze=&Apache::lonnet::str2hash($subresult);
        !           225: 	return $analyze_cache{$key} = \%analyze;
        !           226:     }
        !           227: 
        !           228:     sub get_order {
        !           229: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
        !           230: 	my $analyze = &get_analyze($symb,$uname,$udom);
        !           231: 	return $analyze->{"$partid.$respid.shown"};
        !           232:     }
        !           233: 
        !           234:     sub get_radiobutton_correct_foil {
        !           235: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
        !           236: 	my $analyze = &get_analyze($symb,$uname,$udom);
        !           237: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
        !           238: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
        !           239: 		return $foil;
        !           240: 	    }
        !           241: 	}
        !           242:     }
1.148     albertel  243: }
1.428.2.1! albertel  244: 
1.118     ng        245: #--- Clean response type for display
1.335     albertel  246: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    247: #        response types only.
1.118     ng        248: sub cleanRecord {
1.336     albertel  249:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    250: 	$uname,$udom) = @_;
1.398     albertel  251:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  252:     if ($response =~ /^(option|rank)$/) {
                    253: 	my %answer=&Apache::lonnet::str2hash($answer);
                    254: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    255: 	my ($toprow,$bottomrow);
                    256: 	foreach my $foil (@$order) {
                    257: 	    if ($grading{$foil} == 1) {
                    258: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    259: 	    } else {
                    260: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    261: 	    }
1.398     albertel  262: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  263: 	}
                    264: 	return '<blockquote><table border="1">'.
                    265: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  266: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  267: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    268:     } elsif ($response eq 'match') {
                    269: 	my %answer=&Apache::lonnet::str2hash($answer);
                    270: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    271: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    272: 	my ($toprow,$middlerow,$bottomrow);
                    273: 	foreach my $foil (@$order) {
                    274: 	    my $item=shift(@items);
                    275: 	    if ($grading{$foil} == 1) {
                    276: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  277: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  278: 	    } else {
                    279: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  280: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  281: 	    }
1.398     albertel  282: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        283: 	}
1.126     ng        284: 	return '<blockquote><table border="1">'.
1.148     albertel  285: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  286: 	    '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
1.148     albertel  287: 	    $middlerow.'</tr>'.
1.398     albertel  288: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  289: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    290:     } elsif ($response eq 'radiobutton') {
                    291: 	my %answer=&Apache::lonnet::str2hash($answer);
                    292: 	my ($toprow,$bottomrow);
1.428.2.1! albertel  293: 	my $correct = 
        !           294: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
        !           295: 	foreach my $foil (@$order) {
1.148     albertel  296: 	    if (exists($answer{$foil})) {
1.428.2.1! albertel  297: 		if ($foil eq $correct) {
1.148     albertel  298: 		    $toprow.='<td><b>true</b></td>';
                    299: 		} else {
                    300: 		    $toprow.='<td><i>true</i></td>';
                    301: 		}
                    302: 	    } else {
                    303: 		$toprow.='<td>false</td>';
                    304: 	    }
1.398     albertel  305: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  306: 	}
                    307: 	return '<blockquote><table border="1">'.
                    308: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  309: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  310: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    311:     } elsif ($response eq 'essay') {
1.257     albertel  312: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        313: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  314: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    315: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        316: 
1.257     albertel  317: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    318: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    319: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    320: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    321: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    322: 	    $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        323: 	}
1.166     albertel  324: 	$answer =~ s-\n-<br />-g;
                    325: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  326:     } elsif ( $response eq 'organic') {
                    327: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    328: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    329: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    330: 	return $result;
1.335     albertel  331:     } elsif ( $response eq 'Task') {
                    332: 	if ( $answer eq 'SUBMITTED') {
                    333: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  334: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  335: 	    return $result;
                    336: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    337: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    338: 			       keys(%{$record}));
                    339: 	    return join('<br />',($version,@matches));
                    340: 			       
                    341: 			       
                    342: 	} else {
                    343: 	    my $result =
                    344: 		'<p>'
                    345: 		.&mt('Overall result: [_1]',
                    346: 		     $record->{$version."resource.$respid.$partid.status"})
                    347: 		.'</p>';
                    348: 	    
                    349: 	    $result .= '<ul>';
                    350: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    351: 			     keys(%{$record}));
                    352: 	    foreach my $grade (sort(@grade)) {
                    353: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    354: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    355: 				     $dim, $record->{$grade}).
                    356: 			  '</li>';
                    357: 	    }
                    358: 	    $result.='</ul>';
                    359: 	    return $result;
                    360: 	}
                    361:        
1.122     ng        362:     }
1.118     ng        363:     return $answer;
                    364: }
                    365: 
                    366: #-- A couple of common js functions
                    367: sub commonJSfunctions {
                    368:     my $request = shift;
                    369:     $request->print(<<COMMONJSFUNCTIONS);
                    370: <script type="text/javascript" language="javascript">
                    371:     function radioSelection(radioButton) {
                    372: 	var selection=null;
                    373: 	if (radioButton.length > 1) {
                    374: 	    for (var i=0; i<radioButton.length; i++) {
                    375: 		if (radioButton[i].checked) {
                    376: 		    return radioButton[i].value;
                    377: 		}
                    378: 	    }
                    379: 	} else {
                    380: 	    if (radioButton.checked) return radioButton.value;
                    381: 	}
                    382: 	return selection;
                    383:     }
                    384: 
                    385:     function pullDownSelection(selectOne) {
                    386: 	var selection="";
                    387: 	if (selectOne.length > 1) {
                    388: 	    for (var i=0; i<selectOne.length; i++) {
                    389: 		if (selectOne[i].selected) {
                    390: 		    return selectOne[i].value;
                    391: 		}
                    392: 	    }
                    393: 	} else {
1.138     albertel  394:             // only one value it must be the selected one
                    395: 	    return selectOne.value;
1.118     ng        396: 	}
                    397:     }
                    398: </script>
                    399: COMMONJSFUNCTIONS
                    400: }
                    401: 
1.44      ng        402: #--- Dumps the class list with usernames,list of sections,
                    403: #--- section, ids and fullnames for each user.
                    404: sub getclasslist {
1.76      ng        405:     my ($getsec,$filterlist) = @_;
1.291     albertel  406:     my @getsec;
                    407:     if (!ref($getsec)) {
                    408: 	if ($getsec ne '' && $getsec ne 'all') {
                    409: 	    @getsec=($getsec);
                    410: 	}
                    411:     } else {
                    412: 	@getsec=@{$getsec};
                    413:     }
                    414:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
                    415: 
1.56      matthew   416:     my $classlist=&Apache::loncoursedata::get_classlist();
1.49      albertel  417:     # Bail out if we were unable to get the classlist
1.56      matthew   418:     return if (! defined($classlist));
                    419:     #
                    420:     my %sections;
                    421:     my %fullnames;
1.205     matthew   422:     foreach my $student (keys(%$classlist)) {
                    423:         my $end      = 
                    424:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    425:         my $start    = 
                    426:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    427:         my $id       = 
                    428:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    429:         my $section  = 
                    430:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    431:         my $fullname = 
                    432:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    433:         my $status   = 
                    434:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.76      ng        435: 	# filter students according to status selected
1.257     albertel  436: 	if ($filterlist && $env{'form.Status'} ne 'Any') {
                    437: 	    if ($env{'form.Status'} ne $status) {
1.205     matthew   438: 		delete ($classlist->{$student});
1.76      ng        439: 		next;
                    440: 	    }
                    441: 	}
1.205     matthew   442: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  443: 	if (&canview($section)) {
1.291     albertel  444: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  445: 		$sections{$section}++;
1.205     matthew   446: 		$fullnames{$student}=$fullname;
1.103     albertel  447: 	    } else {
1.205     matthew   448: 		delete($classlist->{$student});
1.103     albertel  449: 	    }
                    450: 	} else {
1.205     matthew   451: 	    delete($classlist->{$student});
1.103     albertel  452: 	}
1.44      ng        453:     }
                    454:     my %seen = ();
1.56      matthew   455:     my @sections = sort(keys(%sections));
                    456:     return ($classlist,\@sections,\%fullnames);
1.44      ng        457: }
                    458: 
1.103     albertel  459: sub canmodify {
                    460:     my ($sec)=@_;
                    461:     if ($perm{'mgr'}) {
                    462: 	if (!defined($perm{'mgr_section'})) {
                    463: 	    # can modify whole class
                    464: 	    return 1;
                    465: 	} else {
                    466: 	    if ($sec eq $perm{'mgr_section'}) {
                    467: 		#can modify the requested section
                    468: 		return 1;
                    469: 	    } else {
                    470: 		# can't modify the request section
                    471: 		return 0;
                    472: 	    }
                    473: 	}
                    474:     }
                    475:     #can't modify
                    476:     return 0;
                    477: }
                    478: 
                    479: sub canview {
                    480:     my ($sec)=@_;
                    481:     if ($perm{'vgr'}) {
                    482: 	if (!defined($perm{'vgr_section'})) {
                    483: 	    # can modify whole class
                    484: 	    return 1;
                    485: 	} else {
                    486: 	    if ($sec eq $perm{'vgr_section'}) {
                    487: 		#can modify the requested section
                    488: 		return 1;
                    489: 	    } else {
                    490: 		# can't modify the request section
                    491: 		return 0;
                    492: 	    }
                    493: 	}
                    494:     }
                    495:     #can't modify
                    496:     return 0;
                    497: }
                    498: 
1.44      ng        499: #--- Retrieve the grade status of a student for all the parts
                    500: sub student_gradeStatus {
1.324     albertel  501:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  502:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        503:     my %partstatus = ();
                    504:     foreach (@$partlist) {
1.128     ng        505: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        506: 	$status              = 'nothing' if ($status eq '');
                    507: 	$partstatus{$_}      = $status;
                    508: 	my $subkey           = "resource.$_.submitted_by";
                    509: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    510:     }
                    511:     return %partstatus;
                    512: }
                    513: 
1.45      ng        514: # hidden form and javascript that calls the form
                    515: # Use by verifyscript and viewgrades
                    516: # Shows a student's view of problem and submission
                    517: sub jscriptNform {
1.324     albertel  518:     my ($symb) = @_;
1.45      ng        519:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    520: 	'    function viewOneStudent(user,domain) {'."\n".
                    521: 	'	document.onestudent.student.value = user;'."\n".
                    522: 	'	document.onestudent.userdom.value = domain;'."\n".
                    523: 	'	document.onestudent.submit();'."\n".
                    524: 	'    }'."\n".
                    525: 	'</script>'."\n";
                    526:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  527: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  528: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    529: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
                    530: 	'<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.45      ng        531: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    532: 	'<input type="hidden" name="student" value="" />'."\n".
                    533: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    534: 	'</form>'."\n";
                    535:     return $jscript;
                    536: }
1.39      ng        537: 
1.315     bowersj2  538: # Given the score (as a number [0-1] and the weight) what is the final
                    539: # point value? This function will round to the nearest tenth, third,
                    540: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  541: sub compute_points {
1.315     bowersj2  542:     my ($score, $weight) = @_;
                    543:     
                    544:     my $tolerance = .00001;
                    545:     my $points = $score * $weight;
                    546: 
                    547:     # Check for nearness to 1/x.
                    548:     my $check_for_nearness = sub {
                    549:         my ($factor) = @_;
                    550:         my $num = ($points * $factor) + $tolerance;
                    551:         my $floored_num = floor($num);
1.316     albertel  552:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  553:             return $floored_num / $factor;
                    554:         }
                    555:         return $points;
                    556:     };
                    557: 
                    558:     $points = $check_for_nearness->(10);
                    559:     $points = $check_for_nearness->(3);
                    560:     $points = $check_for_nearness->(4);
                    561:     
                    562:     return $points;
                    563: }
                    564: 
1.44      ng        565: #------------------ End of general use routines --------------------
1.87      www       566: 
                    567: #
                    568: # Find most similar essay
                    569: #
                    570: 
                    571: sub most_similar {
1.426     albertel  572:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       573: 
                    574: # ignore spaces and punctuation
                    575: 
                    576:     $uessay=~s/\W+/ /gs;
                    577: 
1.282     www       578: # ignore empty submissions (occuring when only files are sent)
                    579: 
                    580:     unless ($uessay=~/\w+/) { return ''; }
                    581: 
1.87      www       582: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       583:     my $limit=0.6;
1.87      www       584:     my $sname='';
                    585:     my $sdom='';
                    586:     my $scrsid='';
                    587:     my $sessay='';
                    588: # go through all essays ...
1.426     albertel  589:     foreach my $tkey (keys(%$old_essays)) {
                    590: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       591: # ... except the same student
1.426     albertel  592:         next if (($tname eq $uname) && ($tdom eq $udom));
                    593: 	my $tessay=$old_essays->{$tkey};
                    594: 	$tessay=~s/\W+/ /gs;
1.87      www       595: # String similarity gives up if not even limit
1.426     albertel  596: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       597: # Found one
1.426     albertel  598: 	if ($tsimilar>$limit) {
                    599: 	    $limit=$tsimilar;
                    600: 	    $sname=$tname;
                    601: 	    $sdom=$tdom;
                    602: 	    $scrsid=$tcrsid;
                    603: 	    $sessay=$old_essays->{$tkey};
                    604: 	}
1.87      www       605:     }
1.88      www       606:     if ($limit>0.6) {
1.87      www       607:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    608:     } else {
                    609:        return ('','','','',0);
                    610:     }
                    611: }
                    612: 
1.44      ng        613: #-------------------------------------------------------------------
                    614: 
                    615: #------------------------------------ Receipt Verification Routines
1.45      ng        616: #
1.44      ng        617: #--- Check whether a receipt number is valid.---
                    618: sub verifyreceipt {
                    619:     my $request  = shift;
                    620: 
1.257     albertel  621:     my $courseid = $env{'request.course.id'};
1.184     www       622:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  623: 	$env{'form.receipt'};
1.44      ng        624:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  625:     my ($symb)   = &get_symb($request);
1.44      ng        626: 
1.398     albertel  627:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
                    628: 	$receipt.'</h3></span>'."\n".
                    629: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
1.44      ng        630: 
                    631:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   632:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  633:     
                    634:     my $receiptparts=0;
1.390     albertel  635:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    636: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  637:     my $parts=['0'];
1.324     albertel  638:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.294     albertel  639:     foreach (sort 
                    640: 	     {
                    641: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    642: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    643: 		 }
                    644: 		 return $a cmp $b;
                    645: 	     } (keys(%$fullname))) {
1.44      ng        646: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  647: 	foreach my $part (@$parts) {
                    648: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
                    649: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
                    650: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  651: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  652: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    653: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    654: 		if ($receiptparts) {
                    655: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    656: 		}
                    657: 		$contents.='</tr>'."\n";
                    658: 		
                    659: 		$matches++;
                    660: 	    }
1.44      ng        661: 	}
                    662:     }
                    663:     if ($matches == 0) {
                    664: 	$string = $title.'No match found for the above receipt.';
                    665:     } else {
1.324     albertel  666: 	$string = &jscriptNform($symb).$title.
1.44      ng        667: 	    'The above receipt matches the following student'.
                    668: 	    ($matches <= 1 ? '.' : 's.')."\n".
                    669: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                    670: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
                    671: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
                    672: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
1.177     albertel  673: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
                    674: 	if ($receiptparts) {
                    675: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
                    676: 	}
                    677: 	$string.='</tr>'."\n".$contents.
1.44      ng        678: 	    '</table></td></tr></table>'."\n";
                    679:     }
1.324     albertel  680:     return $string.&show_grading_menu_form($symb);
1.44      ng        681: }
                    682: 
                    683: #--- This is called by a number of programs.
                    684: #--- Called from the Grading Menu - View/Grade an individual student
                    685: #--- Also called directly when one clicks on the subm button 
                    686: #    on the problem page.
1.30      ng        687: sub listStudents {
1.41      ng        688:     my ($request) = shift;
1.49      albertel  689: 
1.324     albertel  690:     my ($symb) = &get_symb($request);
1.257     albertel  691:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    692:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    693:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                    694:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    695: 
                    696:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    697:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    698: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  699: 
1.398     albertel  700:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
                    701: 	' Submissions for a Student or a Group of Students</span></h3>';
1.118     ng        702: 
1.324     albertel  703:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  704: 
1.45      ng        705:     $request->print(<<LISTJAVASCRIPT);
                    706: <script type="text/javascript" language="javascript">
1.110     ng        707:     function checkSelect(checkBox) {
                    708: 	var ctr=0;
                    709: 	var sense="";
                    710: 	if (checkBox.length > 1) {
                    711: 	    for (var i=0; i<checkBox.length; i++) {
                    712: 		if (checkBox[i].checked) {
                    713: 		    ctr++;
                    714: 		}
                    715: 	    }
                    716: 	    sense = "a student or group of students";
                    717: 	} else {
                    718: 	    if (checkBox.checked) {
                    719: 		ctr = 1;
                    720: 	    }
                    721: 	    sense = "the student";
                    722: 	}
                    723: 	if (ctr == 0) {
1.126     ng        724: 	    alert("Please select "+sense+" before clicking on the Next button.");
1.110     ng        725: 	    return false;
                    726: 	}
                    727: 	document.gradesub.submit();
                    728:     }
                    729: 
                    730:     function reLoadList(formname) {
1.112     ng        731: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        732: 	formname.command.value = 'submission';
                    733: 	formname.submit();
                    734:     }
1.45      ng        735: </script>
                    736: LISTJAVASCRIPT
                    737: 
1.118     ng        738:     &commonJSfunctions($request);
1.41      ng        739:     $request->print($result);
1.39      ng        740: 
1.401     albertel  741:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    742:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  743:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
                    744: 	"\n".$table.
1.401     albertel  745: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.267     albertel  746: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
                    747: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
                    748: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
                    749: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
1.401     albertel  750: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
1.49      albertel  751: 	'&nbsp;<b>Submissions: </b>'."\n";
1.257     albertel  752:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.267     albertel  753: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
1.49      albertel  754:     }
1.110     ng        755: 
1.257     albertel  756:     my $saveStatus = $env{'form.Status'} eq '' ? 'Active' : $env{'form.Status'};
                    757:     $env{'form.Status'} = $saveStatus;
1.110     ng        758: 
1.267     albertel  759:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
                    760: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
                    761: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
1.348     bowersj2  762: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
                    763:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
                    764:         '<option value="1">Whole Points</option>'.
                    765:         '<option value=".5">Half Points</option>'.
1.349     albertel  766:         '<option value=".25">Quarter Points</option>'.
                    767:         '<option value=".1">Tenths of a Point</option>'.
1.348     bowersj2  768:         '</select>'.
                    769: 
1.45      ng        770: 	'<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
                    771: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  772: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    773: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    774: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    775: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  776: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        777: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    778: 
1.257     albertel  779:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
                    780: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng        781:     } else {
                    782: 	$gradeTable.='<b>Student Status:</b> '.
                    783: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
                    784:     }
1.112     ng        785: 
1.126     ng        786:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    787: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
1.110     ng        788: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  789: 
                    790: # checkall buttons
                    791:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        792:     $gradeTable.='<input type="button" '."\n".
1.45      ng        793: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.249     albertel  794: 	'value="Next->" /> <br />'."\n";
                    795:     $gradeTable.=&check_buttons();
1.401     albertel  796:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
1.249     albertel  797:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
1.45      ng        798:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
1.110     ng        799: 	'<table border="0"><tr bgcolor="#e6ffff">';
                    800:     my $loop = 0;
                    801:     while ($loop < 2) {
1.126     ng        802: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
1.250     albertel  803: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
1.301     albertel  804: 	if ($env{'form.showgrading'} eq 'yes' 
                    805: 	    && $submitonly ne 'queued'
                    806: 	    && $submitonly ne 'all') {
1.110     ng        807: 	    foreach (sort(@$partlist)) {
1.324     albertel  808: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
1.207     albertel  809: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
                    810: 		    ' Status&nbsp;</b></td>';
1.110     ng        811: 	    }
1.301     albertel  812: 	} elsif ($submitonly eq 'queued') {
                    813: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
1.110     ng        814: 	}
                    815: 	$loop++;
1.126     ng        816: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        817:     }
1.45      ng        818:     $gradeTable.='</tr>'."\n";
1.41      ng        819: 
1.45      ng        820:     my $ctr = 0;
1.294     albertel  821:     foreach my $student (sort 
                    822: 			 {
                    823: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    824: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    825: 			     }
                    826: 			     return $a cmp $b;
                    827: 			 }
                    828: 			 (keys(%$fullname))) {
1.41      ng        829: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  830: 
1.110     ng        831: 	my %status = ();
1.301     albertel  832: 
                    833: 	if ($submitonly eq 'queued') {
                    834: 	    my %queue_status = 
                    835: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    836: 							$udom,$uname);
                    837: 	    next if (!defined($queue_status{'gradingqueue'}));
                    838: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    839: 	}
                    840: 
                    841: 	if ($env{'form.showgrading'} eq 'yes' 
                    842: 	    && $submitonly ne 'queued'
                    843: 	    && $submitonly ne 'all') {
1.324     albertel  844: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  845: 	    my $submitted = 0;
1.164     albertel  846: 	    my $graded = 0;
1.248     albertel  847: 	    my $incorrect = 0;
1.110     ng        848: 	    foreach (keys(%status)) {
1.145     albertel  849: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  850: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    851: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    852: 		
1.110     ng        853: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    854: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  855: 		    $submitted = 0;
1.150     albertel  856: 		    my ($part)=split(/\./,$partid);
1.110     ng        857: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  858: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        859: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    860: 		}
1.41      ng        861: 	    }
1.248     albertel  862: 	    
1.156     albertel  863: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    864: 				     $submitonly eq 'incorrect' ||
                    865: 				     $submitonly eq 'graded'));
1.248     albertel  866: 	    next if (!$graded && ($submitonly eq 'graded'));
                    867: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        868: 	}
1.34      ng        869: 
1.45      ng        870: 	$ctr++;
1.249     albertel  871: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    872: 
1.104     albertel  873: 	if ( $perm{'vgr'} eq 'F' ) {
1.110     ng        874: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
1.126     ng        875: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  876:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    877:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    878: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    879: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
                    880: 	       '&nbsp;'.$section.'</td>'."\n";
1.110     ng        881: 
1.257     albertel  882: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        883: 		foreach (sort keys(%status)) {
                    884: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  885: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        886: 		}
1.41      ng        887: 	    }
1.126     ng        888: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.110     ng        889: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
1.41      ng        890: 	}
                    891:     }
1.110     ng        892:     if ($ctr%2 ==1) {
1.126     ng        893: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel  894: 	    if ($env{'form.showgrading'} eq 'yes' 
                    895: 		&& $submitonly ne 'queued'
                    896: 		&& $submitonly ne 'all') {
1.110     ng        897: 		foreach (@$partlist) {
                    898: 		    $gradeTable.='<td>&nbsp;</td>';
                    899: 		}
1.301     albertel  900: 	    } elsif ($submitonly eq 'queued') {
                    901: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng        902: 	    }
                    903: 	$gradeTable.='</tr>';
                    904:     }
                    905: 
1.249     albertel  906:     $gradeTable.='</table></td></tr></table>'."\n".
1.45      ng        907: 	'<input type="button" '.
                    908: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng        909: 	'value="Next->" /></form>'."\n";
1.45      ng        910:     if ($ctr == 0) {
1.96      albertel  911: 	my $num_students=(scalar(keys(%$fullname)));
                    912: 	if ($num_students eq 0) {
1.398     albertel  913: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel  914: 	} else {
1.171     albertel  915: 	    my $submissions='submissions';
                    916: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                    917: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel  918: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel  919: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel  920: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel  921: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel  922: 	}
1.46      ng        923:     } elsif ($ctr == 1) {
                    924: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
1.45      ng        925:     }
1.324     albertel  926:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng        927:     $request->print($gradeTable);
1.44      ng        928:     return '';
1.10      ng        929: }
                    930: 
1.44      ng        931: #---- Called from the listStudents routine
1.249     albertel  932: 
                    933: sub check_script {
                    934:     my ($form, $type)=@_;
                    935:     my $chkallscript='<script type="text/javascript">
                    936:     function checkall() {
                    937:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    938:             ele = document.forms.'.$form.'.elements[i];
                    939:             if (ele.name == "'.$type.'") {
                    940:             document.forms.'.$form.'.elements[i].checked=true;
                    941:                                        }
                    942:         }
                    943:     }
                    944: 
                    945:     function checksec() {
                    946:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    947:             ele = document.forms.'.$form.'.elements[i];
                    948:            string = document.forms.'.$form.'.chksec.value;
                    949:            if
                    950:           (ele.value.indexOf(":::SECTION"+string)>0) {
                    951:               document.forms.'.$form.'.elements[i].checked=true;
                    952:             }
                    953:         }
                    954:     }
                    955: 
                    956: 
                    957:     function uncheckall() {
                    958:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    959:             ele = document.forms.'.$form.'.elements[i];
                    960:             if (ele.name == "'.$type.'") {
                    961:             document.forms.'.$form.'.elements[i].checked=false;
                    962:                                        }
                    963:         }
                    964:     }
                    965: 
                    966: </script>'."\n";
                    967:     return $chkallscript;
                    968: }
                    969: 
                    970: sub check_buttons {
                    971:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                    972:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                    973:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                    974:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                    975:     return $buttons;
                    976: }
                    977: 
1.44      ng        978: #     Displays the submissions for one student or a group of students
1.34      ng        979: sub processGroup {
1.41      ng        980:     my ($request)  = shift;
                    981:     my $ctr        = 0;
1.155     albertel  982:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng        983:     my $total      = scalar(@stuchecked)-1;
1.45      ng        984: 
1.396     banghart  985:     foreach my $student (@stuchecked) {
                    986: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel  987: 	$env{'form.student'}        = $uname;
                    988: 	$env{'form.userdom'}        = $udom;
                    989: 	$env{'form.fullname'}       = $fullname;
1.41      ng        990: 	&submission($request,$ctr,$total);
                    991: 	$ctr++;
                    992:     }
                    993:     return '';
1.35      ng        994: }
1.34      ng        995: 
1.44      ng        996: #------------------------------------------------------------------------------------
                    997: #
                    998: #-------------------------- Next few routines handles grading by student, essentially
                    999: #                           handles essay response type problem/part
                   1000: #
                   1001: #--- Javascript to handle the submission page functionality ---
                   1002: sub sub_page_js {
                   1003:     my $request = shift;
                   1004:     $request->print(<<SUBJAVASCRIPT);
                   1005: <script type="text/javascript" language="javascript">
1.71      ng       1006:     function updateRadio(formname,id,weight) {
1.125     ng       1007: 	var gradeBox = formname["GD_BOX"+id];
                   1008: 	var radioButton = formname["RADVAL"+id];
                   1009: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1010: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1011: 	gradeBox.value = pts;
                   1012: 	var resetbox = false;
                   1013: 	if (isNaN(pts) || pts < 0) {
                   1014: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1015: 	    for (var i=0; i<radioButton.length; i++) {
                   1016: 		if (radioButton[i].checked) {
                   1017: 		    gradeBox.value = i;
                   1018: 		    resetbox = true;
                   1019: 		}
                   1020: 	    }
                   1021: 	    if (!resetbox) {
                   1022: 		formtextbox.value = "";
                   1023: 	    }
                   1024: 	    return;
1.44      ng       1025: 	}
1.71      ng       1026: 
                   1027: 	if (pts > weight) {
                   1028: 	    var resp = confirm("You entered a value ("+pts+
                   1029: 			       ") greater than the weight for the part. Accept?");
                   1030: 	    if (resp == false) {
1.125     ng       1031: 		gradeBox.value = oldpts;
1.71      ng       1032: 		return;
                   1033: 	    }
1.44      ng       1034: 	}
1.13      albertel 1035: 
1.71      ng       1036: 	for (var i=0; i<radioButton.length; i++) {
                   1037: 	    radioButton[i].checked=false;
                   1038: 	    if (pts == i && pts != "") {
                   1039: 		radioButton[i].checked=true;
                   1040: 	    }
                   1041: 	}
                   1042: 	updateSelect(formname,id);
1.125     ng       1043: 	formname["stores"+id].value = "0";
1.41      ng       1044:     }
1.5       albertel 1045: 
1.72      ng       1046:     function writeBox(formname,id,pts) {
1.125     ng       1047: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1048: 	if (checkSolved(formname,id) == 'update') {
                   1049: 	    gradeBox.value = pts;
                   1050: 	} else {
1.125     ng       1051: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1052: 	    gradeBox.value = oldpts;
1.125     ng       1053: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1054: 	    for (var i=0; i<radioButton.length; i++) {
                   1055: 		radioButton[i].checked=false;
1.72      ng       1056: 		if (i == oldpts) {
1.71      ng       1057: 		    radioButton[i].checked=true;
                   1058: 		}
                   1059: 	    }
1.41      ng       1060: 	}
1.125     ng       1061: 	formname["stores"+id].value = "0";
1.71      ng       1062: 	updateSelect(formname,id);
                   1063: 	return;
1.41      ng       1064:     }
1.44      ng       1065: 
1.71      ng       1066:     function clearRadBox(formname,id) {
                   1067: 	if (checkSolved(formname,id) == 'noupdate') {
                   1068: 	    updateSelect(formname,id);
                   1069: 	    return;
                   1070: 	}
1.125     ng       1071: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1072: 	for (var i=0; i<gradeSelect.length; i++) {
                   1073: 	    if (gradeSelect[i].selected) {
                   1074: 		var selectx=i;
                   1075: 	    }
                   1076: 	}
1.125     ng       1077: 	var stores = formname["stores"+id];
1.71      ng       1078: 	if (selectx == stores.value) { return };
1.125     ng       1079: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1080: 	gradeBox.value = "";
1.125     ng       1081: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1082: 	for (var i=0; i<radioButton.length; i++) {
                   1083: 	    radioButton[i].checked=false;
                   1084: 	}
                   1085: 	stores.value = selectx;
                   1086:     }
1.5       albertel 1087: 
1.71      ng       1088:     function checkSolved(formname,id) {
1.125     ng       1089: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1090: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1091: 	    if (!reply) {return "noupdate";}
1.120     ng       1092: 	    formname.overRideScore.value = 'yes';
1.41      ng       1093: 	}
1.71      ng       1094: 	return "update";
1.13      albertel 1095:     }
1.71      ng       1096: 
                   1097:     function updateSelect(formname,id) {
1.125     ng       1098: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1099: 	return;
1.41      ng       1100:     }
1.33      ng       1101: 
1.121     ng       1102: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1103:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1104: 	formname.gradeOpt.value = val;
1.71      ng       1105: 	if (val == "Save & Next") {
                   1106: 	    for (i=0;i<=total;i++) {
                   1107: 		for (j=0;j<parttot;j++) {
1.125     ng       1108: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1109: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1110: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1111: 			if (points == "") {
1.125     ng       1112: 			    var name = formname["name"+i].value;
1.129     ng       1113: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1114: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1115: 					       ", part "+partid+". Continue?");
1.71      ng       1116: 			    if (resp == false) {
1.125     ng       1117: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1118: 				return false;
                   1119: 			    }
                   1120: 			}
                   1121: 		    }
                   1122: 		    
                   1123: 		}
                   1124: 	    }
                   1125: 	    
                   1126: 	}
1.121     ng       1127: 	if (val == "Grade Student") {
                   1128: 	    formname.showgrading.value = "yes";
                   1129: 	    if (formname.Status.value == "") {
                   1130: 		formname.Status.value = "Active";
                   1131: 	    }
                   1132: 	    formname.studentNo.value = total;
                   1133: 	}
1.120     ng       1134: 	formname.submit();
                   1135:     }
                   1136: 
1.71      ng       1137: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1138:     function checkSubmitPage(formname,total) {
                   1139: 	noscore = new Array(100);
                   1140: 	var ptr = 0;
                   1141: 	for (i=1;i<total;i++) {
1.125     ng       1142: 	    var partid = formname["q_"+i].value;
1.127     ng       1143: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1144: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1145: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1146: 		if (points == "" && status != "correct_by_student") {
                   1147: 		    noscore[ptr] = i;
                   1148: 		    ptr++;
                   1149: 		}
                   1150: 	    }
                   1151: 	}
                   1152: 	if (ptr != 0) {
                   1153: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1154: 	    var prolist = "";
                   1155: 	    if (ptr == 1) {
                   1156: 		prolist = noscore[0];
                   1157: 	    } else {
                   1158: 		var i = 0;
                   1159: 		while (i < ptr-1) {
                   1160: 		    prolist += noscore[i]+", ";
                   1161: 		    i++;
                   1162: 		}
                   1163: 		prolist += "and "+noscore[i];
                   1164: 	    }
                   1165: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1166: 	    if (resp == false) {
                   1167: 		return false;
                   1168: 	    }
                   1169: 	}
1.45      ng       1170: 
1.71      ng       1171: 	formname.submit();
                   1172:     }
                   1173: </script>
                   1174: SUBJAVASCRIPT
                   1175: }
1.45      ng       1176: 
1.71      ng       1177: #--- javascript for essay type problem --
                   1178: sub sub_page_kw_js {
                   1179:     my $request = shift;
1.80      ng       1180:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1181:     &commonJSfunctions($request);
1.350     albertel 1182: 
1.351     albertel 1183:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1184:     <script text="text/javascript">
                   1185:     function checkInput() {
                   1186:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1187:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1188:       var usrctr = document.msgcenter.usrctr.value;
                   1189:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1190:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1191: 
                   1192:       var msgchk = "";
                   1193:       if (document.msgcenter.subchk.checked) {
                   1194:          msgchk = "msgsub,";
                   1195:       }
                   1196:       var includemsg = 0;
                   1197:       for (var i=1; i<=nmsg; i++) {
                   1198:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1199:           var frmmsg = document.msgcenter["msg"+i];
                   1200:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1201:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1202:           showflg.value = "1";
                   1203:           var chkbox = document.msgcenter["msgn"+i];
                   1204:           if (chkbox.checked) {
                   1205:              msgchk += "savemsg"+i+",";
                   1206:              includemsg = 1;
                   1207:           }
                   1208:       }
                   1209:       if (document.msgcenter.newmsgchk.checked) {
                   1210:          msgchk += "newmsg"+usrctr;
                   1211:          includemsg = 1;
                   1212:       }
                   1213:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1214:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1215:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1216:       includemsg.value = msgchk;
                   1217: 
                   1218:       self.close()
                   1219: 
                   1220:     }
                   1221:     </script>
                   1222: INNERJS
                   1223: 
1.351     albertel 1224:     my $inner_js_highlight_central=<<INNERJS;
                   1225:  <script type="text/javascript">
                   1226:     function updateChoice(flag) {
                   1227:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1228:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1229:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1230:       opener.document.SCORE.refresh.value = "on";
                   1231:       if (opener.document.SCORE.keywords.value!=""){
                   1232:          opener.document.SCORE.submit();
                   1233:       }
                   1234:       self.close()
                   1235:     }
                   1236: </script>
                   1237: INNERJS
                   1238: 
                   1239:     my $start_page_msg_central = 
                   1240:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1241: 				       {'js_ready'  => 1,
                   1242: 					'only_body' => 1,
                   1243: 					'bgcolor'   =>'#FFFFFF',});
                   1244:     my $end_page_msg_central = 
                   1245: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1246: 
                   1247: 
                   1248:     my $start_page_highlight_central = 
                   1249:         &Apache::loncommon::start_page('Highlight Central',
                   1250: 				       $inner_js_highlight_central,
1.350     albertel 1251: 				       {'js_ready'  => 1,
                   1252: 					'only_body' => 1,
                   1253: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1254:     my $end_page_highlight_central = 
1.350     albertel 1255: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1256: 
1.219     www      1257:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1258:     $docopen=~s/^document\.//;
1.71      ng       1259:     $request->print(<<SUBJAVASCRIPT);
                   1260: <script type="text/javascript" language="javascript">
1.45      ng       1261: 
1.44      ng       1262: //===================== Show list of keywords ====================
1.122     ng       1263:   function keywords(formname) {
                   1264:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1265:     if (nret==null) return;
1.122     ng       1266:     formname.keywords.value = nret;
1.44      ng       1267: 
1.122     ng       1268:     if (formname.keywords.value != "") {
1.128     ng       1269: 	formname.refresh.value = "on";
1.122     ng       1270: 	formname.submit();
1.44      ng       1271:     }
                   1272:     return;
                   1273:   }
                   1274: 
                   1275: //===================== Script to view submitted by ==================
                   1276:   function viewSubmitter(submitter) {
                   1277:     document.SCORE.refresh.value = "on";
                   1278:     document.SCORE.NCT.value = "1";
                   1279:     document.SCORE.unamedom0.value = submitter;
                   1280:     document.SCORE.submit();
                   1281:     return;
                   1282:   }
                   1283: 
                   1284: //===================== Script to add keyword(s) ==================
                   1285:   function getSel() {
                   1286:     if (document.getSelection) txt = document.getSelection();
                   1287:     else if (document.selection) txt = document.selection.createRange().text;
                   1288:     else return;
                   1289:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1290:     if (cleantxt=="") {
1.46      ng       1291: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1292: 	return;
                   1293:     }
                   1294:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1295:     if (nret==null) return;
1.127     ng       1296:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1297:     if (document.SCORE.keywords.value != "") {
1.127     ng       1298: 	document.SCORE.refresh.value = "on";
1.44      ng       1299: 	document.SCORE.submit();
                   1300:     }
                   1301:     return;
                   1302:   }
                   1303: 
                   1304: //====================== Script for composing message ==============
1.80      ng       1305:    // preload images
                   1306:    img1 = new Image();
                   1307:    img1.src = "$iconpath/mailbkgrd.gif";
                   1308:    img2 = new Image();
                   1309:    img2.src = "$iconpath/mailto.gif";
                   1310: 
1.44      ng       1311:   function msgCenter(msgform,usrctr,fullname) {
                   1312:     var Nmsg  = msgform.savemsgN.value;
                   1313:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1314:     var subject = msgform.msgsub.value;
1.127     ng       1315:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1316:     re = /msgsub/;
                   1317:     var shwsel = "";
                   1318:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1319:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1320:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1321:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1322: 	var testmsg = "savemsg"+i+",";
                   1323: 	re = new RegExp(testmsg,"g");
1.44      ng       1324: 	shwsel = "";
                   1325: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1326: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1327: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1328: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1329: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1330:     }
1.125     ng       1331:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1332:     shwsel = "";
                   1333:     re = /newmsg/;
                   1334:     if (re.test(msgchk)) { shwsel = "checked" }
                   1335:     newMsg(newmsg,shwsel);
                   1336:     msgTail(); 
                   1337:     return;
                   1338:   }
                   1339: 
1.123     ng       1340:   function checkEntities(strx) {
                   1341:     if (strx.length == 0) return strx;
                   1342:     var orgStr = ["&", "<", ">", '"']; 
                   1343:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1344:     var counter = 0;
                   1345:     while (counter < 4) {
                   1346: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1347: 	counter++;
                   1348:     }
                   1349:     return strx;
                   1350:   }
                   1351: 
                   1352:   function strReplace(strx, orgStr, newStr) {
                   1353:     return strx.split(orgStr).join(newStr);
                   1354:   }
                   1355: 
1.44      ng       1356:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1357:     var height = 70*Nmsg+250;
1.44      ng       1358:     var scrollbar = "no";
                   1359:     if (height > 600) {
                   1360: 	height = 600;
                   1361: 	scrollbar = "yes";
                   1362:     }
1.118     ng       1363:     var xpos = (screen.width-600)/2;
                   1364:     xpos = (xpos < 0) ? '0' : xpos;
                   1365:     var ypos = (screen.height-height)/2-30;
                   1366:     ypos = (ypos < 0) ? '0' : ypos;
                   1367: 
1.206     albertel 1368:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1369:     pWin.focus();
                   1370:     pDoc = pWin.document;
1.219     www      1371:     pDoc.$docopen;
1.351     albertel 1372:     pDoc.write('$start_page_msg_central');
1.76      ng       1373: 
                   1374:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1375:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.398     albertel 1376:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
1.76      ng       1377: 
                   1378:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1379:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1380:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1.44      ng       1381: }
                   1382:     function displaySubject(msg,shwsel) {
1.76      ng       1383:     pDoc = pWin.document;
                   1384:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1385:     pDoc.write("<td>Subject</td>");
                   1386:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1387:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1.44      ng       1388: }
                   1389: 
1.72      ng       1390:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1391:     pDoc = pWin.document;
                   1392:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1393:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
                   1394:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1395:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1.44      ng       1396: }
                   1397: 
                   1398:   function newMsg(newmsg,shwsel) {
1.76      ng       1399:     pDoc = pWin.document;
                   1400:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1401:     pDoc.write("<td align=\\"center\\">New</td>");
                   1402:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1403:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1.44      ng       1404: }
                   1405: 
                   1406:   function msgTail() {
1.76      ng       1407:     pDoc = pWin.document;
                   1408:     pDoc.write("</table>");
                   1409:     pDoc.write("</td></tr></table>&nbsp;");
                   1410:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1411:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1412:     pDoc.write("</form>");
1.351     albertel 1413:     pDoc.write('$end_page_msg_central');
1.128     ng       1414:     pDoc.close();
1.44      ng       1415: }
                   1416: 
                   1417: //====================== Script for keyword highlight options ==============
                   1418:   function kwhighlight() {
                   1419:     var kwclr    = document.SCORE.kwclr.value;
                   1420:     var kwsize   = document.SCORE.kwsize.value;
                   1421:     var kwstyle  = document.SCORE.kwstyle.value;
                   1422:     var redsel = "";
                   1423:     var grnsel = "";
                   1424:     var blusel = "";
                   1425:     if (kwclr=="red")   {var redsel="checked"};
                   1426:     if (kwclr=="green") {var grnsel="checked"};
                   1427:     if (kwclr=="blue")  {var blusel="checked"};
                   1428:     var sznsel = "";
                   1429:     var sz1sel = "";
                   1430:     var sz2sel = "";
                   1431:     if (kwsize=="0")  {var sznsel="checked"};
                   1432:     if (kwsize=="+1") {var sz1sel="checked"};
                   1433:     if (kwsize=="+2") {var sz2sel="checked"};
                   1434:     var synsel = "";
                   1435:     var syisel = "";
                   1436:     var sybsel = "";
                   1437:     if (kwstyle=="")    {var synsel="checked"};
                   1438:     if (kwstyle=="<i>") {var syisel="checked"};
                   1439:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1440:     highlightCentral();
                   1441:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1442:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1443:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1444:     highlightend();
                   1445:     return;
                   1446:   }
                   1447: 
                   1448:   function highlightCentral() {
1.76      ng       1449: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1450:     var xpos = (screen.width-400)/2;
                   1451:     xpos = (xpos < 0) ? '0' : xpos;
                   1452:     var ypos = (screen.height-330)/2-30;
                   1453:     ypos = (ypos < 0) ? '0' : ypos;
                   1454: 
1.206     albertel 1455:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1456:     hwdWin.focus();
                   1457:     var hDoc = hwdWin.document;
1.219     www      1458:     hDoc.$docopen;
1.351     albertel 1459:     hDoc.write('$start_page_highlight_central');
1.76      ng       1460:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.398     albertel 1461:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
1.76      ng       1462: 
                   1463:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1464:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1465:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1.44      ng       1466:   }
                   1467: 
                   1468:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1469:     var hDoc = hwdWin.document;
                   1470:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1471:     hDoc.write("<td align=\\"left\\">");
                   1472:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
                   1473:     hDoc.write("<td align=\\"left\\">");
                   1474:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
                   1475:     hDoc.write("<td align=\\"left\\">");
                   1476:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
                   1477:     hDoc.write("</tr>");
1.44      ng       1478:   }
                   1479: 
                   1480:   function highlightend() { 
1.76      ng       1481:     var hDoc = hwdWin.document;
                   1482:     hDoc.write("</table>");
                   1483:     hDoc.write("</td></tr></table>&nbsp;");
                   1484:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1485:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1486:     hDoc.write("</form>");
1.351     albertel 1487:     hDoc.write('$end_page_highlight_central');
1.128     ng       1488:     hDoc.close();
1.44      ng       1489:   }
                   1490: 
                   1491: </script>
                   1492: SUBJAVASCRIPT
                   1493: }
                   1494: 
1.349     albertel 1495: sub get_increment {
1.348     bowersj2 1496:     my $increment = $env{'form.increment'};
                   1497:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1498:         $increment != .1) {
                   1499:         $increment = 1;
                   1500:     }
                   1501:     return $increment;
                   1502: }
                   1503: 
1.71      ng       1504: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1505: sub gradeBox {
1.322     albertel 1506:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1507:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1508: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1509: 	'/check.gif" height="16" border="0" />';
                   1510:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
                   1511:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
1.398     albertel 1512: 		  '<span class="LC_info">problem weight assigned by computer</span>');
1.71      ng       1513:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1514:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1515: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1516:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.324     albertel 1517:     my $display_part=&get_display_part($partid,$symb);
1.270     albertel 1518:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1519: 				       [$partid]);
                   1520:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1521:     if ($last_resets{$partid}) {
                   1522:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1523:     }
1.71      ng       1524:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1525: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1526:     my $ctr = 0;
1.348     bowersj2 1527:     my $thisweight = 0;
1.349     albertel 1528:     my $increment = &get_increment();
1.71      ng       1529:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1530:     while ($thisweight<=$wgt) {
1.381     albertel 1531: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1532: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1533: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1534: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1535: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1536:         $thisweight += $increment;
1.71      ng       1537: 	$ctr++;
                   1538:     }
                   1539:     $result.='</tr></table>';
                   1540:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1541:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1542: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1543: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1544: 	$wgt.')" /></td>'."\n";
                   1545:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1546: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1547: 	' </td><td>'."\n";
                   1548:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1549: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1550:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1551: 	$result.='<option></option>'.
1.401     albertel 1552: 	    '<option selected="selected">excused</option>';
1.71      ng       1553:     } else {
1.401     albertel 1554: 	$result.='<option selected="selected"></option>'.
1.125     ng       1555: 	    '<option>excused</option>';
1.71      ng       1556:     }
1.125     ng       1557:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1558:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1559:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1560: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1561: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1562: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1563:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1564:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1565:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1566:         $aggtries.'" />'."\n";
1.71      ng       1567:     $result.='</td></tr></table>'."\n";
1.323     banghart 1568:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1569:     return $result;
                   1570: }
1.322     albertel 1571: 
                   1572: sub handback_box {
1.323     banghart 1573:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1574:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1575:     my (@respids);
1.375     albertel 1576:      my @part_response_id = &flatten_responseType($responseType);
                   1577:     foreach my $part_response_id (@part_response_id) {
                   1578:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1579:         if ($part eq $partid) {
1.375     albertel 1580:             push(@respids,$resp);
1.323     banghart 1581:         }
                   1582:     }
1.318     banghart 1583:     my $result;
1.323     banghart 1584:     foreach my $respid (@respids) {
1.322     albertel 1585: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1586: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1587: 	next if (!@$files);
                   1588: 	my $file_counter = 1;
1.313     banghart 1589: 	foreach my $file (@$files) {
1.368     banghart 1590: 	    if ($file =~ /\/portfolio\//) {
                   1591:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1592:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1593:     	        $file_disp = "$name.$ext";
                   1594:     	        $file = $file_path.$file_disp;
                   1595:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1596:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1597:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1598:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.369     banghart 1599:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1.368     banghart 1600:     	        $file_counter++;
                   1601: 	    }
1.322     albertel 1602: 	}
1.313     banghart 1603:     }
1.318     banghart 1604:     return $result;    
1.71      ng       1605: }
1.44      ng       1606: 
1.58      albertel 1607: sub show_problem {
1.382     albertel 1608:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1609:     my $rendered;
1.382     albertel 1610:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1611:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1612:     if ($mode eq 'both' or $mode eq 'text') {
                   1613: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1614: 						       $env{'request.course.id'},
                   1615: 						       undef,\%form);
1.144     albertel 1616:     }
1.58      albertel 1617:     if ($removeform) {
                   1618: 	$rendered=~s|<form(.*?)>||g;
                   1619: 	$rendered=~s|</form>||g;
1.374     albertel 1620: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1621:     }
1.144     albertel 1622:     my $companswer;
                   1623:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1624: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1625: 	$companswer=
                   1626: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1627: 						    $env{'request.course.id'},
                   1628: 						    %form);
1.144     albertel 1629:     }
1.58      albertel 1630:     if ($removeform) {
                   1631: 	$companswer=~s|<form(.*?)>||g;
                   1632: 	$companswer=~s|</form>||g;
1.144     albertel 1633: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1634:     }
                   1635:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1636:     $result.='<table border="0" width="100%">';
1.144     albertel 1637:     if ($viewon) {
                   1638: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1639: 	if ($mode eq 'both' or $mode eq 'text') {
                   1640: 	    $result.='View of the problem - ';
                   1641: 	} else {
                   1642: 	    $result.='Correct answer: ';
                   1643: 	}
1.257     albertel 1644: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1645:     }
                   1646:     if ($mode eq 'both') {
                   1647: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1648: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1649:     } elsif ($mode eq 'text') {
                   1650: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1651:     } elsif ($mode eq 'answer') {
                   1652: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1653:     }
1.58      albertel 1654:     $result.='</td></tr></table>';
                   1655:     $result.='</td></tr></table><br />';
1.71      ng       1656:     return $result;
1.58      albertel 1657: }
1.397     albertel 1658: 
1.396     banghart 1659: sub files_exist {
                   1660:     my ($r, $symb) = @_;
                   1661:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1662: 
1.396     banghart 1663:     foreach my $student (@students) {
                   1664:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1665:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1666: 					      $udom,$uname);
1.396     banghart 1667:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1668:         foreach my $submission (@$string) {
                   1669:             my ($partid,$respid) =
                   1670: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1671:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1672: 					   \%record);
                   1673:             return 1 if (@$files);
1.396     banghart 1674:         }
                   1675:     }
1.397     albertel 1676:     return 0;
1.396     banghart 1677: }
1.397     albertel 1678: 
1.394     banghart 1679: sub download_all_link {
                   1680:     my ($r,$symb) = @_;
1.395     albertel 1681:     my $all_students = 
                   1682: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1683: 
                   1684:     my $parts =
                   1685: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1686: 
1.394     banghart 1687:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1688:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1689:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1690:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1691:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1692: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1693:     return
                   1694: }
1.395     albertel 1695: 
1.44      ng       1696: # --------------------------- show submissions of a student, option to grade 
                   1697: sub submission {
                   1698:     my ($request,$counter,$total) = @_;
                   1699: 
1.257     albertel 1700:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1701:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1702:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1703:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.41      ng       1704: 
1.324     albertel 1705:     my $symb = &get_symb($request); 
                   1706:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1707: 
                   1708:     if (!&canview($usec)) {
1.398     albertel 1709: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1710: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1711: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1712: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1713: 	return;
                   1714:     }
                   1715: 
1.257     albertel 1716:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1717:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1718:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1719:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1720:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1721: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1722: 	'/check.gif" height="16" border="0" />';
1.41      ng       1723: 
1.426     albertel 1724:     my %old_essays;
1.41      ng       1725:     # header info
                   1726:     if ($counter == 0) {
                   1727: 	&sub_page_js($request);
1.257     albertel 1728: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1729: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1730: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1731: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1732: 	    &download_all_link($request, $symb);
                   1733: 	}
1.398     albertel 1734: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
                   1735: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1.118     ng       1736: 
1.257     albertel 1737: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1738: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1739: 		$checkIcon.' symbol.'."\n";
                   1740: 	    $request->print($checkMark);
                   1741: 	}
1.41      ng       1742: 
1.44      ng       1743: 	# option to display problem, only once else it cause problems 
                   1744:         # with the form later since the problem has a form.
1.257     albertel 1745: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1746: 	    my $mode;
1.257     albertel 1747: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1748: 		$mode='both';
1.257     albertel 1749: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1750: 		$mode='text';
1.257     albertel 1751: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1752: 		$mode='answer';
                   1753: 	    }
1.329     albertel 1754: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1755: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1756: 	}
                   1757: 	
1.44      ng       1758: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1759:         # if this subroutine has been called once.
1.41      ng       1760: 	my %keyhash = ();
1.257     albertel 1761: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1762: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1763: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1764: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1765: 
1.257     albertel 1766: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1767: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1768: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1769: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1770: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1771: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1772: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1773: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1774: 	}
1.257     albertel 1775: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.44      ng       1776: 
1.303     banghart 1777: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1778: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1779: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
                   1780: 			'<input type="hidden" name="Status"     value="'.$env{'form.Status'}.'" />'."\n".
1.120     ng       1781: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1782: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1783: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1784: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1785: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1786: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1787: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1788: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1789: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1790: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.326     albertel 1791: 			'<input type="hidden" name="section"    value="'.$env{'form.section'}.'" />'."\n".
                   1792: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1793: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1794: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1795: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1796: 	if ($env{'form.handgrade'} eq 'yes') {
                   1797: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1798: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1799: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1800: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1801: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1802: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1803: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1804: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1805: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1806: 	    }
1.123     ng       1807: 	}
1.41      ng       1808: 	
                   1809: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1810: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1811: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1812: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1813: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1814: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1815: 		'" />'."\n".
                   1816: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1817: 	    $cts++;
                   1818: 	}
                   1819: 	$request->print($prnmsg);
1.32      ng       1820: 
1.257     albertel 1821: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1822: #
                   1823: # Print out the keyword options line
                   1824: #
1.41      ng       1825: 	    $request->print(<<KEYWORDS);
1.38      ng       1826: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1827: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1828: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1829:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1830: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1831: KEYWORDS
1.88      www      1832: #
                   1833: # Load the other essays for similarity check
                   1834: #
1.324     albertel 1835:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1836: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1837: 	    $apath=&escape($apath);
1.88      www      1838: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1839: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1840:         }
                   1841:     }
1.44      ng       1842: 
1.257     albertel 1843:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.71      ng       1844: 	$request->print('<br /><br /><br />') if ($counter > 0);
1.144     albertel 1845: 	my $mode;
1.257     albertel 1846: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1847: 	    $mode='both';
1.257     albertel 1848: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1849: 	    $mode='text';
1.257     albertel 1850: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1851: 	    $mode='answer';
                   1852: 	}
1.329     albertel 1853: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1854: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1855:     }
1.144     albertel 1856: 
1.257     albertel 1857:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1858:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1859: 
1.44      ng       1860:     # Display student info
1.41      ng       1861:     $request->print(($counter == 0 ? '' : '<br />'));
1.326     albertel 1862:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
                   1863: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1.44      ng       1864: 
1.257     albertel 1865:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1.45      ng       1866:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1867: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1868: 
1.118     ng       1869:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.45      ng       1870:     my @col_fullnames;
1.56      matthew  1871:     my ($classlist,$fullname);
1.257     albertel 1872:     if ($env{'form.handgrade'} eq 'yes') {
1.80      ng       1873: 	($classlist,undef,$fullname) = &getclasslist('all','0');
1.41      ng       1874: 	for (keys (%$handgrade)) {
1.44      ng       1875: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1.57      matthew  1876: 					    '.maxcollaborators',
                   1877:                                             $symb,$udom,$uname);
                   1878: 	    next if ($ncol <= 0);
                   1879:             s/\_/\./g;
                   1880:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
1.86      ng       1881:             my @goodcollaborators = ();
                   1882:             my @badcollaborators  = ();
                   1883: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
                   1884: 		$_ =~ s/[\$\^\(\)]//g;
                   1885: 		next if ($_ eq '');
1.80      ng       1886: 		my ($co_name,$co_dom) = split /\@|:/,$_;
1.86      ng       1887: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1.80      ng       1888: 		next if ($co_name eq $uname && $co_dom eq $udom);
1.86      ng       1889: 		# Doing this grep allows 'fuzzy' specification
                   1890: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
                   1891: 		if (! scalar(@Matches)) {
                   1892: 		    push @badcollaborators,$_;
                   1893: 		} else {
                   1894: 		    push @goodcollaborators, @Matches;
                   1895: 		}
1.80      ng       1896: 	    }
1.86      ng       1897:             if (scalar(@goodcollaborators) != 0) {
1.57      matthew  1898:                 $result.='<b>Collaborators: </b>';
1.86      ng       1899:                 foreach (@goodcollaborators) {
                   1900: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
                   1901: 		    push @col_fullnames, $givenn.' '.$lastname;
                   1902: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
                   1903: 		}
1.57      matthew  1904:                 $result.='<br />'."\n";
1.150     albertel 1905: 		my ($part)=split(/\./,$_);
1.86      ng       1906: 		$result.='<input type="hidden" name="collaborator'.$counter.
1.150     albertel 1907: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
                   1908: 		    "\n";
1.86      ng       1909: 	    }
                   1910: 	    if (scalar(@badcollaborators) > 0) {
                   1911: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1912: 		$result.='This student has submitted ';
                   1913: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
                   1914: 		$result .= ': '.join(', ',@badcollaborators);
                   1915: 		$result .= '</td></tr></table>';
                   1916: 	    }         
                   1917: 	    if (scalar(@badcollaborators > $ncol)) {
                   1918: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1919: 		$result .= 'This student has submitted too many '.
                   1920: 		    'collaborators.  Maximum is '.$ncol.'.';
                   1921: 		$result .= '</td></tr></table>';
                   1922: 	    }
1.41      ng       1923: 	}
                   1924:     }
1.44      ng       1925:     $request->print($result."\n");
1.33      ng       1926: 
1.44      ng       1927:     # print student answer/submission
                   1928:     # Options are (1) Handgaded submission only
                   1929:     #             (2) Last submission, includes submission that is not handgraded 
                   1930:     #                  (for multi-response type part)
                   1931:     #             (3) Last submission plus the parts info
                   1932:     #             (4) The whole record for this student
1.257     albertel 1933:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 1934: 	my ($string,$timestamp)= &get_last_submission(\%record);
                   1935: 	my $lastsubonly=''.
                   1936: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
                   1937: 	     $$timestamp)."</td></tr>\n";
                   1938: 	if ($$timestamp eq '') {
                   1939: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
                   1940: 	} else {
                   1941: 	    my %seenparts;
1.375     albertel 1942: 	    my @part_response_id = &flatten_responseType($responseType);
                   1943: 	    foreach my $part (@part_response_id) {
1.393     albertel 1944: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   1945: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   1946: 
1.375     albertel 1947: 		my ($partid,$respid) = @{ $part };
1.324     albertel 1948: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 1949: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 1950: 		    if (exists($seenparts{$partid})) { next; }
                   1951: 		    $seenparts{$partid}=1;
1.207     albertel 1952: 		    my $submitby='<b>Part:</b> '.$display_part.
                   1953: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 1954: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 1955: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 1956: 			'\');" target="_self">'.
1.257     albertel 1957: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 1958: 		    $request->print($submitby);
                   1959: 		    next;
                   1960: 		}
                   1961: 		my $responsetype = $responseType->{$partid}->{$respid};
                   1962: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.207     albertel 1963: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1.398     albertel 1964: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   1965: 			' )</span>&nbsp; &nbsp;'.
                   1966: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1.151     albertel 1967: 		    next;
                   1968: 		}
                   1969: 		foreach (@$string) {
                   1970: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1.375     albertel 1971: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.151     albertel 1972: 		    my ($ressub,$subval) = split(/:/,$_,2);
                   1973: 		    # Similarity check
                   1974: 		    my $similar='';
1.257     albertel 1975: 		    if($env{'form.checkPlag'}){
1.151     albertel 1976: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 1977: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 1978: 			if ($osim) {
                   1979: 			    $osim=int($osim*100.0);
1.426     albertel 1980: 			    my %old_course_desc = 
                   1981: 				&Apache::lonnet::coursedescription($ocrsid,
                   1982: 								   {'one_time' => 1});
                   1983: 
                   1984: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 1985: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 1986: 				    $osim,
                   1987: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 1988: 				    $oname,$odom,
1.426     albertel 1989: 				    $old_course_desc{'description'},
1.427     albertel 1990: 				    $old_course_desc{'num'},
1.426     albertel 1991: 				    $old_course_desc{'domain'}).
1.398     albertel 1992: 				'</span></h3><blockquote><i>'.
1.151     albertel 1993: 				&keywords_highlight($oessay).
                   1994: 				'</i></blockquote><hr />';
                   1995: 			}
1.150     albertel 1996: 		    }
1.151     albertel 1997: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 1998: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   1999: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2000: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2001: 			my $display_part=&get_display_part($partid,$symb);
1.403     albertel 2002: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   2003: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2004: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2005: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2006: 			if (@$files) {
1.398     albertel 2007: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1.303     banghart 2008: 			    my $file_counter = 0;
1.313     banghart 2009: 			    foreach my $file (@$files) {
1.303     banghart 2010: 			        $file_counter ++;
1.232     albertel 2011: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2012: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2013: 			    }
1.236     albertel 2014: 			    $lastsubonly.='<br />';
1.41      ng       2015: 			}
1.151     albertel 2016: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   2017: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2018: 					 $respid,\%record,$order);
                   2019: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       2020: 		    }
                   2021: 		}
                   2022: 	    }
1.151     albertel 2023: 	}
                   2024: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   2025: 	$request->print($lastsubonly);
1.257     albertel 2026:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2027: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2028: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2029:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2030: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2031: 								 $env{'request.course.id'},
1.44      ng       2032: 								 $last,'.submission',
                   2033: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2034:     }
1.120     ng       2035: 
1.121     ng       2036:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2037: 	.$udom.'" />'."\n");
1.41      ng       2038:     
1.44      ng       2039:     # return if view submission with no grading option
1.257     albertel 2040:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2041: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2042: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2043: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 2044: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 2045: 	if (($env{'form.command'} eq 'submission') || 
                   2046: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2047: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2048: 	}
1.180     albertel 2049: 	$request->print($toGrade);
1.41      ng       2050: 	return;
1.180     albertel 2051:     } else {
                   2052: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       2053:     }
1.33      ng       2054: 
1.121     ng       2055:     # essay grading message center
1.257     albertel 2056:     if ($env{'form.handgrade'} eq 'yes') {
                   2057: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2058: 	my $msgfor = $givenn.' '.$lastname;
                   2059: 	if (scalar(@col_fullnames) > 0) {
                   2060: 	    my $lastone = pop @col_fullnames;
                   2061: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   2062: 	}
                   2063: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       2064: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2065: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2066: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2067: 	    ',\''.$msgfor.'\');" target="_self">'.
1.350     albertel 2068: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
                   2069: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2070: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2071: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2072: 	    '<br />&nbsp;('.
                   2073: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       2074: 	$request->print($result);
1.118     ng       2075:     }
1.300     albertel 2076:     if ($perm{'vgr'}) {
1.297     www      2077: 	$request->print('<br />'.
1.300     albertel 2078: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2079: 						   $uname,$udom,'check'));
1.297     www      2080:     }
1.300     albertel 2081:     if ($perm{'opa'}) {
1.297     www      2082: 	$request->print('<br />'.
1.300     albertel 2083: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2084: 					 $uname,$udom,$symb,'check'));
1.297     www      2085:     }
1.41      ng       2086: 
                   2087:     my %seen = ();
                   2088:     my @partlist;
1.129     ng       2089:     my @gradePartRespid;
1.375     albertel 2090:     my @part_response_id = &flatten_responseType($responseType);
                   2091:     foreach my $part_response_id (@part_response_id) {
                   2092:     	my ($partid,$respid) = @{ $part_response_id };
                   2093: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2094: 	next if ($seen{$partid} > 0);
1.41      ng       2095: 	$seen{$partid}++;
1.393     albertel 2096: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2097: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2098: 	push @partlist,$partid;
1.129     ng       2099: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2100: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2101:     }
1.45      ng       2102:     $result='<input type="hidden" name="partlist'.$counter.
                   2103: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2104:     $result.='<input type="hidden" name="gradePartRespid'.
                   2105: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2106:     my $ctr = 0;
                   2107:     while ($ctr < scalar(@partlist)) {
                   2108: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2109: 	    $partlist[$ctr].'" />'."\n";
                   2110: 	$ctr++;
                   2111:     }
                   2112:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       2113: 
                   2114:     # print end of form
                   2115:     if ($counter == $total) {
1.297     www      2116: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2117: 	$endform.='<input type="button" value="Save & Next" '.
                   2118: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2119: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2120: 	my $ntstu ='<select name="NTSTU">'.
                   2121: 	    '<option>1</option><option>2</option>'.
                   2122: 	    '<option>3</option><option>5</option>'.
                   2123: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2124: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2125: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.119     ng       2126: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2127: 	$endform.='<input type="button" value="Previous" '.
1.417     albertel 2128: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.126     ng       2129: 	    '<input type="button" value="Next" '.
1.417     albertel 2130: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.126     ng       2131: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2132:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2133:             "' name='increment' />";
1.45      ng       2134: 	$endform.='</td><tr></table></form>';
1.324     albertel 2135: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2136: 	$request->print($endform);
                   2137:     }
                   2138:     return '';
1.38      ng       2139: }
                   2140: 
1.44      ng       2141: #--- Retrieve the last submission for all the parts
1.38      ng       2142: sub get_last_submission {
1.119     ng       2143:     my ($returnhash)=@_;
1.46      ng       2144:     my (@string,$timestamp);
1.119     ng       2145:     if ($$returnhash{'version'}) {
1.46      ng       2146: 	my %lasthash=();
                   2147: 	my ($version);
1.119     ng       2148: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2149: 	    foreach my $key (sort(split(/\:/,
                   2150: 					$$returnhash{$version.':keys'}))) {
                   2151: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2152: 		$timestamp = 
                   2153: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2154: 	    }
                   2155: 	}
1.397     albertel 2156: 	foreach my $key (keys(%lasthash)) {
                   2157: 	    next if ($key !~ /\.submission$/);
                   2158: 
                   2159: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2160: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2161: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2162: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2163: 	}
                   2164:     }
1.397     albertel 2165:     if (!@string) {
                   2166: 	$string[0] =
1.398     albertel 2167: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2168:     }
                   2169:     return (\@string,\$timestamp);
1.38      ng       2170: }
1.35      ng       2171: 
1.44      ng       2172: #--- High light keywords, with style choosen by user.
1.38      ng       2173: sub keywords_highlight {
1.44      ng       2174:     my $string    = shift;
1.257     albertel 2175:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2176:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2177:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2178:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2179:     foreach my $keyword (@keylist) {
                   2180: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2181:     }
                   2182:     return $string;
1.38      ng       2183: }
1.36      ng       2184: 
1.44      ng       2185: #--- Called from submission routine
1.38      ng       2186: sub processHandGrade {
1.41      ng       2187:     my ($request) = shift;
1.324     albertel 2188:     my $symb   = &get_symb($request);
                   2189:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2190:     my $button = $env{'form.gradeOpt'};
                   2191:     my $ngrade = $env{'form.NCT'};
                   2192:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2193:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2194:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2195: 
1.44      ng       2196:     if ($button eq 'Save & Next') {
                   2197: 	my $ctr = 0;
                   2198: 	while ($ctr < $ngrade) {
1.257     albertel 2199: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2200: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2201: 	    if ($errorflag eq 'no_score') {
                   2202: 		$ctr++;
                   2203: 		next;
                   2204: 	    }
1.104     albertel 2205: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2206: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2207: 		$ctr++;
                   2208: 		next;
                   2209: 	    }
1.257     albertel 2210: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2211: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2212: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2213:             my ($feedurl,$showsymb) =
                   2214: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2215: 	    my $messagetail;
1.62      albertel 2216: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2217: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2218: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2219: 		$subject.=' ['.$restitle.']';
1.44      ng       2220: 		my (@msgnum) = split(/,/,$includemsg);
                   2221: 		foreach (@msgnum) {
1.257     albertel 2222: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2223: 		}
1.80      ng       2224: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2225: 		if ($env{'form.withgrades'.$ctr}) {
                   2226: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2227: 		    $messagetail = " for <a href=\"".
1.418     albertel 2228: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2229: 		}
                   2230: 		$msgstatus = 
                   2231:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2232: 						     $message.$messagetail,
1.418     albertel 2233:                                                      undef,$feedurl,undef,
1.386     raeburn  2234:                                                      undef,undef,$showsymb,
                   2235:                                                      $restitle);
                   2236: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2237: 				$msgstatus);
1.44      ng       2238: 	    }
1.257     albertel 2239: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2240: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2241: 		foreach my $collabstr (@collabstrs) {
                   2242: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2243: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2244: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2245: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2246: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2247: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2248: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2249: 			    next;
1.418     albertel 2250: 			} elsif ($message ne '') {
                   2251: 			    my ($baseurl,$showsymb) = 
                   2252: 				&get_feedurl_and_symb($symb,$collaborator,
                   2253: 						      $udom);
                   2254: 			    if ($env{'form.withgrades'.$ctr}) {
                   2255: 				$messagetail = " for <a href=\"".
1.386     raeburn  2256:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2257: 			    }
1.418     albertel 2258: 			    $msgstatus = 
                   2259: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2260: 			}
1.44      ng       2261: 		    }
                   2262: 		}
                   2263: 	    }
                   2264: 	    $ctr++;
                   2265: 	}
                   2266:     }
                   2267: 
1.257     albertel 2268:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2269: 	# Keywords sorted in alphabatical order
1.257     albertel 2270: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2271: 	my %keyhash = ();
1.257     albertel 2272: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2273: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2274: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2275: 	$env{'form.keywords'} = join(' ',@keywords);
                   2276: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2277: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2278: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2279: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2280: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2281: 
                   2282: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2283: 	# New messages are saved in env for the next student.
1.119     ng       2284: 	# All messages are saved in nohist_handgrade.db
                   2285: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2286: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2287: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2288: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2289: 		$idx++;
                   2290: 	    }
                   2291: 	    $ctr++;
1.41      ng       2292: 	}
1.119     ng       2293: 	$ctr = 0;
                   2294: 	while ($ctr < $ngrade) {
1.257     albertel 2295: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2296: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2297: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2298: 		$idx++;
                   2299: 	    }
                   2300: 	    $ctr++;
1.41      ng       2301: 	}
1.257     albertel 2302: 	$env{'form.savemsgN'} = --$idx;
                   2303: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2304: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2305: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2306:     }
1.44      ng       2307:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2308:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2309:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2310: 	my ($ctr,$total) = (0,0);
                   2311: 	while ($ctr < $ngrade) {
1.257     albertel 2312: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2313: 	    $ctr++;
                   2314: 	}
1.257     albertel 2315: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2316: 	$ctr = 0;
                   2317: 	while ($ctr < $total) {
1.257     albertel 2318: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2319: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2320: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2321: 	    &submission($request,$ctr,$total-1);
1.41      ng       2322: 	    $ctr++;
                   2323: 	}
                   2324: 	return '';
                   2325:     }
1.36      ng       2326: 
1.121     ng       2327: # Go directly to grade student - from submission or link from chart page
1.120     ng       2328:     if ($button eq 'Grade Student') {
1.324     albertel 2329: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2330: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2331: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2332: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2333: 	&submission($request,0,0);
                   2334: 	return '';
                   2335:     }
                   2336: 
1.44      ng       2337:     # Get the next/previous one or group of students
1.257     albertel 2338:     my $firststu = $env{'form.unamedom0'};
                   2339:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2340:     my $ctr = 2;
1.41      ng       2341:     while ($laststu eq '') {
1.257     albertel 2342: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2343: 	$ctr++;
                   2344: 	$laststu = $firststu if ($ctr > $ngrade);
                   2345:     }
1.44      ng       2346: 
1.41      ng       2347:     my (@parsedlist,@nextlist);
                   2348:     my ($nextflg) = 0;
1.294     albertel 2349:     foreach (sort 
                   2350: 	     {
                   2351: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2352: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2353: 		 }
                   2354: 		 return $a cmp $b;
                   2355: 	     } (keys(%$fullname))) {
1.41      ng       2356: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2357: 	    push @parsedlist,$_;
                   2358: 	}
                   2359: 	$nextflg = 1 if ($_ eq $laststu);
                   2360: 	if ($button eq 'Previous') {
                   2361: 	    last if ($_ eq $firststu);
                   2362: 	    push @parsedlist,$_;
                   2363: 	}
                   2364:     }
                   2365:     $ctr = 0;
                   2366:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2367:     my ($partlist) = &response_type($symb);
1.41      ng       2368:     foreach my $student (@parsedlist) {
1.257     albertel 2369: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2370: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2371: 	
                   2372: 	if ($submitonly eq 'queued') {
                   2373: 	    my %queue_status = 
                   2374: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2375: 							$udom,$uname);
                   2376: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2377: 	}
                   2378: 
1.156     albertel 2379: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2380: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2381: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2382: 	    my $submitted = 0;
1.248     albertel 2383: 	    my $ungraded = 0;
                   2384: 	    my $incorrect = 0;
1.145     albertel 2385: 	    foreach (keys(%status)) {
                   2386: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2387: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2388: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2389: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2390: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2391: 		    $submitted = 0;
                   2392: 		}
1.41      ng       2393: 	    }
1.156     albertel 2394: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2395: 				     $submitonly eq 'incorrect' ||
                   2396: 				     $submitonly eq 'graded'));
1.248     albertel 2397: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2398: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2399: 	}
                   2400: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2401: 	last if ($ctr == $ntstu);
1.41      ng       2402: 	$ctr++;
                   2403:     }
1.36      ng       2404: 
1.41      ng       2405:     $ctr = 0;
                   2406:     my $total = scalar(@nextlist)-1;
1.39      ng       2407: 
1.41      ng       2408:     foreach (sort @nextlist) {
                   2409: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2410: 	$env{'form.student'}  = $uname;
                   2411: 	$env{'form.userdom'}  = $udom;
                   2412: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2413: 	&submission($request,$ctr,$total);
                   2414: 	$ctr++;
                   2415:     }
                   2416:     if ($total < 0) {
1.398     albertel 2417: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
1.41      ng       2418: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2419: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2420: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2421: 	$request->print($the_end);
                   2422:     }
                   2423:     return '';
1.38      ng       2424: }
1.36      ng       2425: 
1.44      ng       2426: #---- Save the score and award for each student, if changed
1.38      ng       2427: sub saveHandGrade {
1.324     albertel 2428:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2429:     my @version_parts;
1.104     albertel 2430:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2431: 					   $env{'request.course.id'});
1.104     albertel 2432:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2433:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2434:     my @parts_graded;
1.77      ng       2435:     my %newrecord  = ();
                   2436:     my ($pts,$wgt) = ('','');
1.269     raeburn  2437:     my %aggregate = ();
                   2438:     my $aggregateflag = 0;
1.301     albertel 2439:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2440:     foreach my $new_part (@parts) {
1.337     banghart 2441: 	#collaborator ($submi may vary for different parts
1.259     banghart 2442: 	if ($submitter && $new_part ne $part) { next; }
                   2443: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2444: 	if ($dropMenu eq 'excused') {
1.259     banghart 2445: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2446: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2447: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2448: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2449: 		}
1.364     banghart 2450: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2451: 	    }
1.125     ng       2452: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2453: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2454: 	    foreach my $key (keys (%record)) {
1.259     banghart 2455: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2456: 	    }
1.259     banghart 2457: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2458: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2459:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2460: 
                   2461:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2462: 					       [$new_part]);
                   2463:             my $aggtries =$totaltries;
1.269     raeburn  2464:             if ($last_resets{$new_part}) {
1.270     albertel 2465:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2466: 					   $new_part);
1.269     raeburn  2467:             }
1.270     albertel 2468: 
                   2469:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2470:             if ($aggtries > 0) {
1.327     albertel 2471:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2472:                 $aggregateflag = 1;
                   2473:             }
1.125     ng       2474: 	} elsif ($dropMenu eq '') {
1.259     banghart 2475: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2476: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2477: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2478: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2479: 		next;
                   2480: 	    }
1.259     banghart 2481: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2482: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2483: 	    my $partial= $pts/$wgt;
1.259     banghart 2484: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2485: 		#do not update score for part if not changed.
1.346     banghart 2486:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2487: 		next;
1.251     banghart 2488: 	    } else {
1.259     banghart 2489: 	        push @parts_graded, $new_part;
1.153     albertel 2490: 	    }
1.259     banghart 2491: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2492: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2493: 	    }
1.259     banghart 2494: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2495: 	    if ($partial == 0) {
1.153     albertel 2496: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2497: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2498: 		}
1.41      ng       2499: 	    } else {
1.153     albertel 2500: 		if ($record{$reckey} ne 'correct_by_override') {
                   2501: 		    $newrecord{$reckey} = 'correct_by_override';
                   2502: 		}
                   2503: 	    }	    
                   2504: 	    if ($submitter && 
1.259     banghart 2505: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2506: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2507: 	    }
1.259     banghart 2508: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2509: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2510: 	}
1.259     banghart 2511: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2512: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2513: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2514: 	        $dropMenu eq 'reset status')
                   2515: 	   {
1.342     banghart 2516: 	    push (@version_parts,$new_part);
1.259     banghart 2517: 	}
1.41      ng       2518:     }
1.301     albertel 2519:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2520:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2521: 
1.344     albertel 2522:     if (%newrecord) {
                   2523:         if (@version_parts) {
1.364     banghart 2524:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2525:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2526: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2527: 	    foreach my $new_part (@version_parts) {
                   2528: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2529: 				$new_part,\%newrecord);
                   2530: 	    }
1.259     banghart 2531:         }
1.44      ng       2532: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2533: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2534: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2535: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2536:     }
1.269     raeburn  2537:     if ($aggregateflag) {
                   2538:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2539: 			      $cdom,$cnum);
1.269     raeburn  2540:     }
1.301     albertel 2541:     return ('',$pts,$wgt);
1.36      ng       2542: }
1.322     albertel 2543: 
1.380     albertel 2544: sub check_and_remove_from_queue {
                   2545:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2546:     my @ungraded_parts;
                   2547:     foreach my $part (@{$parts}) {
                   2548: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2549: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2550: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2551: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2552: 		) {
                   2553: 	    push(@ungraded_parts, $part);
                   2554: 	}
                   2555:     }
                   2556:     if ( !@ungraded_parts ) {
                   2557: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2558: 					       $cnum,$domain,$stuname);
                   2559:     }
                   2560: }
                   2561: 
1.337     banghart 2562: sub handback_files {
                   2563:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2564:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2565:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2566: 
                   2567:     my @part_response_id = &flatten_responseType($responseType);
                   2568:     foreach my $part_response_id (@part_response_id) {
                   2569:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2570: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2571:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2572:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2573:                 my $file_counter = 1;
1.367     albertel 2574: 		my $file_msg;
1.337     banghart 2575:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2576:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2577:                     my ($directory,$answer_file) = 
                   2578:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2579:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2580: 		        &file_name_version_ext($answer_file);
1.355     banghart 2581: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2582: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2583: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2584:                     # fix file name
                   2585:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2586:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2587:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2588:             	                                $save_file_name);
1.337     banghart 2589:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2590:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2591:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2592:                     } else {
1.360     banghart 2593:                         # mark the file as read only
                   2594:                         my @files = ($save_file_name);
1.372     albertel 2595:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2596:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2597: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2598: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2599: 			}
                   2600:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2601: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2602: 
1.337     banghart 2603:                     }
                   2604:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2605:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2606:                     $file_counter++;
                   2607:                 }
1.367     albertel 2608: 		my $subject = "File Handed Back by Instructor ";
                   2609: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2610: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2611: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2612: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2613: 		my ($feedurl,$showsymb) = 
                   2614: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2615:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2616: 		my $msgstatus = 
                   2617:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2618: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2619:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2620:             }
                   2621:         }
1.338     banghart 2622:     return;
1.337     banghart 2623: }
                   2624: 
1.418     albertel 2625: sub get_feedurl_and_symb {
                   2626:     my ($symb,$uname,$udom) = @_;
                   2627:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2628:     $url = &Apache::lonnet::clutter($url);
                   2629:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2630: 					$symb,$udom,$uname);
                   2631:     if ($encrypturl =~ /^yes$/i) {
                   2632: 	&Apache::lonenc::encrypted(\$url,1);
                   2633: 	&Apache::lonenc::encrypted(\$symb,1);
                   2634:     }
                   2635:     return ($url,$symb);
                   2636: }
                   2637: 
1.313     banghart 2638: sub get_submitted_files {
                   2639:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2640:     my @files;
                   2641:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2642:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2643:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2644:     	    push(@files,$file_url.$file);
                   2645:         }
                   2646:     }
                   2647:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2648:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2649:     }
                   2650:     return (\@files);
                   2651: }
1.322     albertel 2652: 
1.269     raeburn  2653: # ----------- Provides number of tries since last reset.
                   2654: sub get_num_tries {
                   2655:     my ($record,$last_reset,$part) = @_;
                   2656:     my $timestamp = '';
                   2657:     my $num_tries = 0;
                   2658:     if ($$record{'version'}) {
                   2659:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2660:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2661:                 $timestamp = $$record{$version.':timestamp'};
                   2662:                 if ($timestamp > $last_reset) {
                   2663:                     $num_tries ++;
                   2664:                 } else {
                   2665:                     last;
                   2666:                 }
                   2667:             }
                   2668:         }
                   2669:     }
                   2670:     return $num_tries;
                   2671: }
                   2672: 
                   2673: # ----------- Determine decrements required in aggregate totals 
                   2674: sub decrement_aggs {
                   2675:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2676:     my %decrement = (
                   2677:                         attempts => 0,
                   2678:                         users => 0,
                   2679:                         correct => 0
                   2680:                     );
                   2681:     $decrement{'attempts'} = $aggtries;
                   2682:     if ($solvedstatus =~ /^correct/) {
                   2683:         $decrement{'correct'} = 1;
                   2684:     }
                   2685:     if ($aggtries == $totaltries) {
                   2686:         $decrement{'users'} = 1;
                   2687:     }
                   2688:     foreach my $type (keys (%decrement)) {
                   2689:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2690:     }
                   2691:     return;
                   2692: }
                   2693: 
                   2694: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2695: sub get_last_resets {
1.270     albertel 2696:     my ($symb,$courseid,$partids) =@_;
                   2697:     my %last_resets;
1.269     raeburn  2698:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2699:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2700:     my @keys;
                   2701:     foreach my $part (@{$partids}) {
                   2702: 	push(@keys,"$symb\0$part\0resettime");
                   2703:     }
                   2704:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2705: 				     $cdom,$cname);
                   2706:     foreach my $part (@{$partids}) {
                   2707: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2708:     }
1.270     albertel 2709:     return %last_resets;
1.269     raeburn  2710: }
                   2711: 
1.251     banghart 2712: # ----------- Handles creating versions for portfolio files as answers
                   2713: sub version_portfiles {
1.343     banghart 2714:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2715:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2716:     my @returned_keys;
1.255     banghart 2717:     my $parts = join('|', @$parts_graded);
1.359     www      2718:     my $portfolio_root = &propath($domain,$stu_name).
                   2719: 	'/userfiles/portfolio';
1.277     albertel 2720:     foreach my $key (keys(%$record)) {
1.259     banghart 2721:         my $new_portfiles;
1.263     banghart 2722:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2723:             my @versioned_portfiles;
1.367     albertel 2724:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2725:             foreach my $file (@portfiles) {
1.306     banghart 2726:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2727:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2728: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2729: 		    &file_name_version_ext($answer_file);
1.306     banghart 2730:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2731:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2732:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2733:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2734:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2735:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2736:                         [$directory.$new_answer],
1.306     banghart 2737:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2738:                 }
1.252     banghart 2739:             }
1.343     banghart 2740:             $$record{$key} = join(',',@versioned_portfiles);
                   2741:             push(@returned_keys,$key);
1.251     banghart 2742:         }
                   2743:     } 
1.343     banghart 2744:     return (@returned_keys);   
1.305     banghart 2745: }
                   2746: 
1.307     banghart 2747: sub get_next_version {
1.341     banghart 2748:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2749:     my $version;
                   2750:     foreach my $row (@$dir_list) {
                   2751:         my ($file) = split(/\&/,$row,2);
                   2752:         my ($file_name,$file_version,$file_ext) =
                   2753: 	    &file_name_version_ext($file);
                   2754:         if (($file_name eq $answer_name) && 
                   2755: 	    ($file_ext eq $answer_ext)) {
                   2756:                 # gets here if filename and extension match, regardless of version
                   2757:                 if ($file_version ne '') {
                   2758:                 # a versioned file is found  so save it for later
                   2759:                 if ($file_version > $version) {
                   2760: 		    $version = $file_version;
                   2761: 	        }
                   2762:             }
                   2763:         }
                   2764:     } 
                   2765:     $version ++;
                   2766:     return($version);
                   2767: }
                   2768: 
1.305     banghart 2769: sub version_selected_portfile {
1.306     banghart 2770:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2771:     my ($answer_name,$answer_ver,$answer_ext) =
                   2772:         &file_name_version_ext($file_name);
                   2773:     my $new_answer;
                   2774:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2775:     if($env{'form.copy'} eq '-1') {
                   2776:         &Apache::lonnet::logthis('problem getting file '.$file_name);
                   2777:         $new_answer = 'problem getting file';
                   2778:     } else {
                   2779:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2780:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2781:                             $stu_name,$domain,'copy',
                   2782: 		        '/portfolio'.$directory.$new_answer);
                   2783:     }    
                   2784:     return ($new_answer);
1.251     banghart 2785: }
                   2786: 
1.304     albertel 2787: sub file_name_version_ext {
                   2788:     my ($file)=@_;
                   2789:     my @file_parts = split(/\./, $file);
                   2790:     my ($name,$version,$ext);
                   2791:     if (@file_parts > 1) {
                   2792: 	$ext=pop(@file_parts);
                   2793: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2794: 	    $version=pop(@file_parts);
                   2795: 	}
                   2796: 	$name=join('.',@file_parts);
                   2797:     } else {
                   2798: 	$name=join('.',@file_parts);
                   2799:     }
                   2800:     return($name,$version,$ext);
                   2801: }
                   2802: 
1.44      ng       2803: #--------------------------------------------------------------------------------------
                   2804: #
                   2805: #-------------------------- Next few routines handles grading by section or whole class
                   2806: #
                   2807: #--- Javascript to handle grading by section or whole class
1.42      ng       2808: sub viewgrades_js {
                   2809:     my ($request) = shift;
                   2810: 
1.41      ng       2811:     $request->print(<<VIEWJAVASCRIPT);
                   2812: <script type="text/javascript" language="javascript">
1.45      ng       2813:    function writePoint(partid,weight,point) {
1.125     ng       2814: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2815: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2816: 	if (point == "textval") {
1.125     ng       2817: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2818: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2819: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2820: 		var resetbox = false;
                   2821: 		for (var i=0; i<radioButton.length; i++) {
                   2822: 		    if (radioButton[i].checked) {
                   2823: 			textbox.value = i;
                   2824: 			resetbox = true;
                   2825: 		    }
                   2826: 		}
                   2827: 		if (!resetbox) {
                   2828: 		    textbox.value = "";
                   2829: 		}
                   2830: 		return;
                   2831: 	    }
1.109     matthew  2832: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2833: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2834: 				   ") greater than the weight for the part. Accept?");
                   2835: 		if (resp == false) {
                   2836: 		    textbox.value = "";
                   2837: 		    return;
                   2838: 		}
                   2839: 	    }
1.42      ng       2840: 	    for (var i=0; i<radioButton.length; i++) {
                   2841: 		radioButton[i].checked=false;
1.109     matthew  2842: 		if (parseFloat(point) == i) {
1.42      ng       2843: 		    radioButton[i].checked=true;
                   2844: 		}
                   2845: 	    }
1.41      ng       2846: 
1.42      ng       2847: 	} else {
1.125     ng       2848: 	    textbox.value = parseFloat(point);
1.42      ng       2849: 	}
1.41      ng       2850: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2851: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2852: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2853: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2854: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2855: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2856: 	    if (saveval != "correct") {
                   2857: 		scorename.value = point;
1.43      ng       2858: 		if (selname[0].selected != true) {
                   2859: 		    selname[0].selected = true;
                   2860: 		}
1.42      ng       2861: 	    }
                   2862: 	}
1.125     ng       2863: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2864:     }
                   2865: 
                   2866:     function writeRadText(partid,weight) {
1.125     ng       2867: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2868: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2869:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2870: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2871: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2872: 	    for (var i=0; i<radioButton.length; i++) {
                   2873: 		radioButton[i].checked=false;
                   2874: 
                   2875: 	    }
                   2876: 	    textbox.value = "";
                   2877: 
                   2878: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2879: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2880: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2881: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2882: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2883: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2884: 		if ((saveval != "correct") || override) {
1.42      ng       2885: 		    scorename.value = "";
1.125     ng       2886: 		    if (selval[1].selected) {
                   2887: 			selname[1].selected = true;
                   2888: 		    } else {
                   2889: 			selname[2].selected = true;
                   2890: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   2891: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   2892: 		    }
1.42      ng       2893: 		}
                   2894: 	    }
1.43      ng       2895: 	} else {
                   2896: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2897: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2898: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2899: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2900: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2901: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2902: 		if ((saveval != "correct") || override) {
1.125     ng       2903: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       2904: 		    selname[0].selected = true;
                   2905: 		}
                   2906: 	    }
                   2907: 	}	    
1.42      ng       2908:     }
                   2909: 
                   2910:     function changeSelect(partid,user) {
1.125     ng       2911: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2912: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       2913: 	var point  = textbox.value;
1.125     ng       2914: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       2915: 
1.109     matthew  2916: 	if (isNaN(point) || parseFloat(point) < 0) {
                   2917: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       2918: 	    textbox.value = "";
                   2919: 	    return;
                   2920: 	}
1.109     matthew  2921: 	if (parseFloat(point) > parseFloat(weight)) {
                   2922: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2923: 			       ") greater than the weight of the part. Accept?");
                   2924: 	    if (resp == false) {
                   2925: 		textbox.value = "";
                   2926: 		return;
                   2927: 	    }
                   2928: 	}
1.42      ng       2929: 	selval[0].selected = true;
                   2930:     }
                   2931: 
                   2932:     function changeOneScore(partid,user) {
1.125     ng       2933: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2934: 	if (selval[1].selected || selval[2].selected) {
                   2935: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   2936: 	    if (selval[2].selected) {
                   2937: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   2938: 	    }
1.269     raeburn  2939:         }
1.42      ng       2940:     }
                   2941: 
                   2942:     function resetEntry(numpart) {
                   2943: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       2944: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   2945: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   2946: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   2947: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       2948: 	    for (var i=0; i<radioButton.length; i++) {
                   2949: 		radioButton[i].checked=false;
                   2950: 
                   2951: 	    }
                   2952: 	    textbox.value = "";
                   2953: 	    selval[0].selected = true;
                   2954: 
                   2955: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2956: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2957: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2958: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2959: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   2960: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   2961: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   2962: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2963: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2964: 		if (saveselval == "excused") {
1.43      ng       2965: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       2966: 		} else {
1.43      ng       2967: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       2968: 		}
                   2969: 	    }
1.41      ng       2970: 	}
1.42      ng       2971:     }
                   2972: 
1.41      ng       2973: </script>
                   2974: VIEWJAVASCRIPT
1.42      ng       2975: }
                   2976: 
1.44      ng       2977: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       2978: sub viewgrades {
                   2979:     my ($request) = shift;
                   2980:     &viewgrades_js($request);
1.41      ng       2981: 
1.324     albertel 2982:     my ($symb) = &get_symb($request);
1.168     albertel 2983:     #need to make sure we have the correct data for later EXT calls, 
                   2984:     #thus invalidate the cache
                   2985:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 2986:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   2987:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 2988:     &Apache::lonnet::clear_EXT_cache_status();
                   2989: 
1.398     albertel 2990:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   2991:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       2992: 
                   2993:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 2994:     $result.=&jscriptNform($symb);
1.41      ng       2995: 
1.44      ng       2996:     #beginning of class grading form
1.41      ng       2997:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 2998: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       2999: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.257     albertel 3000: 	'<input type="hidden" name="section" value="'.$env{'form.section'}.'" />'."\n".
                   3001: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   3002: 	'<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
                   3003: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3004: 
1.126     ng       3005:     my $sectionClass;
1.257     albertel 3006:     if ($env{'form.section'} eq 'all') {
1.126     ng       3007: 	$sectionClass='Class </h3>';
1.257     albertel 3008:     } elsif ($env{'form.section'} eq 'none') {
1.126     ng       3009: 	$sectionClass='Students in no Section </h3>';
1.52      albertel 3010:     } else {
1.257     albertel 3011: 	$sectionClass='Students in Section '.$env{'form.section'}.'</h3>';
1.52      albertel 3012:     }
1.126     ng       3013:     $result.='<h3>Assign Common Grade To '.$sectionClass;
1.52      albertel 3014:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   3015: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       3016:     #radio buttons/text box for assigning points for a section or class.
                   3017:     #handles different parts of a problem
1.375     albertel 3018:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3019:     my %weight = ();
                   3020:     my $ctsparts = 0;
1.41      ng       3021:     $result.='<table border="0">';
1.45      ng       3022:     my %seen = ();
1.375     albertel 3023:     my @part_response_id = &flatten_responseType($responseType);
                   3024:     foreach my $part_response_id (@part_response_id) {
                   3025:     	my ($partid,$respid) = @{ $part_response_id };
                   3026: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3027: 	next if $seen{$partid};
                   3028: 	$seen{$partid}++;
1.375     albertel 3029: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3030: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3031: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3032: 
1.44      ng       3033: 	$result.='<input type="hidden" name="partid_'.
                   3034: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3035: 	$result.='<input type="hidden" name="weight_'.
                   3036: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3037: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 3038: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3039: 	$result.='<table border="0"><tr>';  
1.41      ng       3040: 	my $ctr = 0;
1.42      ng       3041: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3042: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3043: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3044: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3045: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3046: 	    $ctr++;
                   3047: 	}
                   3048: 	$result.='</tr></table>';
1.44      ng       3049: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3050: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3051: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3052: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   3053: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3054: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3055: 		$weight{$partid}.')"> '.
1.401     albertel 3056: 	    '<option selected="selected"> </option>'.
1.125     ng       3057: 	    '<option>excused</option>'.
1.265     www      3058: 	    '<option>reset status</option></select></td>'.
1.266     albertel 3059:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       3060: 	$ctsparts++;
1.41      ng       3061:     }
1.52      albertel 3062:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   3063: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3064:     $result.='<input type="button" value="Revert to Default" '.
1.417     albertel 3065: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
1.41      ng       3066: 
1.44      ng       3067:     #table listing all the students in a section/class
                   3068:     #header of table
1.126     ng       3069:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       3070:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       3071: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       3072: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 3073:     my (@parts) = sort(&getpartlist($symb));
                   3074:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3075:     my @partids = ();
1.41      ng       3076:     foreach my $part (@parts) {
                   3077: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3078: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3079: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3080: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3081:         push(@partids, $partid);
1.324     albertel 3082: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3083: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 3084: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   3085: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       3086: 	    next;
1.207     albertel 3087: 	} else {
                   3088: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3089: 	}
1.53      albertel 3090: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 3091: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       3092:     }
                   3093:     $result.='</tr>';
1.44      ng       3094: 
1.270     albertel 3095:     my %last_resets = 
                   3096: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3097: 
1.41      ng       3098:     #get info for each student
1.44      ng       3099:     #list all the students - with points and grade status
1.257     albertel 3100:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3101:     my $ctr = 0;
1.294     albertel 3102:     foreach (sort 
                   3103: 	     {
                   3104: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3105: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3106: 		 }
                   3107: 		 return $a cmp $b;
                   3108: 	     } (keys(%$fullname))) {
1.126     ng       3109: 	$ctr++;
1.324     albertel 3110: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3111: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3112:     }
                   3113:     $result.='</table></td></tr></table>';
                   3114:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3115:     $result.='<input type="button" value="Save" '.
1.417     albertel 3116: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3117:     if (scalar(%$fullname) eq 0) {
                   3118: 	my $colspan=3+scalar(@parts);
1.398     albertel 3119: 	$result='<span class="LC_warning">There are no students in section "'.$env{'form.section'}.
                   3120: 	    '" with enrollment status "'.$env{'form.Status'}.'" to modify or grade.</span>';
1.96      albertel 3121:     }
1.324     albertel 3122:     $result.=&show_grading_menu_form($symb);
1.41      ng       3123:     return $result;
                   3124: }
                   3125: 
1.44      ng       3126: #--- call by previous routine to display each student
1.41      ng       3127: sub viewstudentgrade {
1.324     albertel 3128:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3129:     my ($uname,$udom) = split(/:/,$student);
                   3130:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3131:     my %aggregates = (); 
1.233     albertel 3132:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3133: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3134: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3135: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3136: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3137: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3138:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3139:     foreach my $apart (@$parts) {
                   3140: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3141: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3142:         $result.='<td align="center">';
1.269     raeburn  3143:         my ($aggtries,$totaltries);
                   3144:         unless (exists($aggregates{$part})) {
1.270     albertel 3145: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3146: 
                   3147: 	    $aggtries = $totaltries;
1.269     raeburn  3148:             if ($$last_resets{$part}) {  
1.270     albertel 3149:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3150: 					   $part);
                   3151:             }
1.269     raeburn  3152:             $result.='<input type="hidden" name="'.
                   3153:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3154:             $result.='<input type="hidden" name="'.
                   3155:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3156:             $aggregates{$part} = 1;
                   3157:         }
1.41      ng       3158: 	if ($type eq 'awarded') {
1.320     albertel 3159: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3160: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3161: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3162: 	    $result.='<input type="text" name="'.
1.89      albertel 3163: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3164: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3165: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3166: 	} elsif ($type eq 'solved') {
                   3167: 	    my ($status,$foo)=split(/_/,$score,2);
                   3168: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3169: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3170: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3171: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3172: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3173: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3174: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3175: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3176: 	    $result.='<option>reset status</option>';
1.126     ng       3177: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3178: 	} else {
                   3179: 	    $result.='<input type="hidden" name="'.
                   3180: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3181: 		    "\n";
1.233     albertel 3182: 	    $result.='<input type="text" name="'.
1.122     ng       3183: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3184: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3185: 	}
                   3186:     }
                   3187:     $result.='</tr>';
                   3188:     return $result;
1.38      ng       3189: }
                   3190: 
1.44      ng       3191: #--- change scores for all the students in a section/class
                   3192: #    record does not get update if unchanged
1.38      ng       3193: sub editgrades {
1.41      ng       3194:     my ($request) = @_;
                   3195: 
1.324     albertel 3196:     my $symb=&get_symb($request);
1.398     albertel 3197:     my $title='<h3><span class="LC_info">Current Grade Status</span></h3>';
                   3198:     $title.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4><br />'."\n";
                   3199:     $title.='<h4><b>Section: </b>'.$env{'form.section'}.'</h4>'."\n";
1.126     ng       3200: 
1.44      ng       3201:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3202:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3203: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3204: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3205: 
                   3206:     my %scoreptr = (
                   3207: 		    'correct'  =>'correct_by_override',
                   3208: 		    'incorrect'=>'incorrect_by_override',
                   3209: 		    'excused'  =>'excused',
                   3210: 		    'ungraded' =>'ungraded_attempted',
                   3211: 		    'nothing'  => '',
                   3212: 		    );
1.257     albertel 3213:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3214: 
1.44      ng       3215:     my (@partid);
                   3216:     my %weight = ();
1.54      albertel 3217:     my %columns = ();
1.44      ng       3218:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3219: 
1.324     albertel 3220:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3221:     my $header;
1.257     albertel 3222:     while ($ctr < $env{'form.totalparts'}) {
                   3223: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3224: 	push @partid,$partid;
1.257     albertel 3225: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3226: 	$ctr++;
1.54      albertel 3227:     }
1.324     albertel 3228:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3229:     foreach my $partid (@partid) {
                   3230: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3231: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3232: 	$columns{$partid}=2;
                   3233: 	foreach my $stores (@parts) {
                   3234: 	    my ($part,$type) = &split_part_type($stores);
                   3235: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3236: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3237: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3238: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3239: 	    $display =~ s/Number of Attempts/Tries/;
                   3240: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3241: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3242: 	    $columns{$partid}+=2;
                   3243: 	}
                   3244:     }
                   3245:     foreach my $partid (@partid) {
1.324     albertel 3246: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3247: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3248: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3249: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3250: 
1.44      ng       3251:     }
                   3252:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3253:     $result .= $header;
1.44      ng       3254:     $result .= '</tr>'."\n";
1.93      albertel 3255:     my $noupdate;
1.126     ng       3256:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3257:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3258: 	my $line;
1.257     albertel 3259: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3260: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3261: 	my %newrecord;
                   3262: 	my $updateflag = 0;
1.281     albertel 3263: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3264: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3265: 	if (!&canmodify($usec)) {
1.126     ng       3266: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3267: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3268: 	    next;
                   3269: 	}
1.269     raeburn  3270:         my %aggregate = ();
                   3271:         my $aggregateflag = 0;
1.281     albertel 3272: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3273: 	foreach (@partid) {
1.257     albertel 3274: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3275: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3276: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3277: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3278: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3279: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3280: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3281: 	    my $score;
                   3282: 	    if ($partial eq '') {
1.257     albertel 3283: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3284: 	    } elsif ($partial > 0) {
                   3285: 		$score = 'correct_by_override';
                   3286: 	    } elsif ($partial == 0) {
                   3287: 		$score = 'incorrect_by_override';
                   3288: 	    }
1.257     albertel 3289: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3290: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3291: 
1.292     albertel 3292: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3293: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3294: 	    if ($dropMenu eq 'reset status' &&
                   3295: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3296: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3297: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3298: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3299: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3300: 		$updateflag = 1;
1.269     raeburn  3301:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3302:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3303:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3304:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3305:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3306:                     $aggregateflag = 1;
                   3307:                 }
1.139     albertel 3308: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3309: 		$updateflag = 1;
                   3310: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3311: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3312: 		$rec_update++;
1.125     ng       3313: 	    }
                   3314: 
1.93      albertel 3315: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3316: 		'<td align="center">'.$awarded.
                   3317: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3318: 
1.54      albertel 3319: 
                   3320: 	    my $partid=$_;
                   3321: 	    foreach my $stores (@parts) {
                   3322: 		my ($part,$type) = &split_part_type($stores);
                   3323: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3324: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3325: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3326: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3327: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3328: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3329: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3330: 		    $updateflag=1;
                   3331: 		}
1.93      albertel 3332: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3333: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3334: 	    }
1.44      ng       3335: 	}
1.93      albertel 3336: 	$line.='</tr>'."\n";
1.301     albertel 3337: 
                   3338: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3339: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3340: 
1.44      ng       3341: 	if ($updateflag) {
                   3342: 	    $count++;
1.257     albertel 3343: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3344: 				    $udom,$uname);
1.301     albertel 3345: 
                   3346: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3347: 					      $cnum,$udom,$uname)) {
                   3348: 		# need to figure out if should be in queue.
                   3349: 		my %record =  
                   3350: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3351: 					     $udom,$uname);
                   3352: 		my $all_graded = 1;
                   3353: 		my $none_graded = 1;
                   3354: 		foreach my $part (@parts) {
                   3355: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3356: 			$all_graded = 0;
                   3357: 		    } else {
                   3358: 			$none_graded = 0;
                   3359: 		    }
                   3360: 		}
                   3361: 
                   3362: 		if ($all_graded || $none_graded) {
                   3363: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3364: 							   $symb,$cdom,$cnum,
                   3365: 							   $udom,$uname);
                   3366: 		}
                   3367: 	    }
                   3368: 
1.126     ng       3369: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3370: 	    $updateCtr++;
1.93      albertel 3371: 	} else {
1.126     ng       3372: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3373: 	    $noupdateCtr++;
1.44      ng       3374: 	}
1.269     raeburn  3375:         if ($aggregateflag) {
                   3376:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3377: 				  $cdom,$cnum);
1.269     raeburn  3378:         }
1.93      albertel 3379:     }
                   3380:     if ($noupdate) {
1.126     ng       3381: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3382: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3383: 	$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       3384:     }
1.72      ng       3385:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3386: 	&show_grading_menu_form ($symb);
1.125     ng       3387:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3388: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3389: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3390:     return $title.$msg.$result;
1.5       albertel 3391: }
1.54      albertel 3392: 
                   3393: sub split_part_type {
                   3394:     my ($partstr) = @_;
                   3395:     my ($temp,@allparts)=split(/_/,$partstr);
                   3396:     my $type=pop(@allparts);
                   3397:     my $part=join('.',@allparts);
                   3398:     return ($part,$type);
                   3399: }
                   3400: 
1.44      ng       3401: #------------- end of section for handling grading by section/class ---------
                   3402: #
                   3403: #----------------------------------------------------------------------------
                   3404: 
1.5       albertel 3405: 
1.44      ng       3406: #----------------------------------------------------------------------------
                   3407: #
                   3408: #-------------------------- Next few routines handles grading by csv upload
                   3409: #
                   3410: #--- Javascript to handle csv upload
1.27      albertel 3411: sub csvupload_javascript_reverse_associate {
1.246     albertel 3412:     my $error1=&mt('You need to specify the username or ID');
                   3413:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3414:   return(<<ENDPICK);
                   3415:   function verify(vf) {
                   3416:     var foundsomething=0;
                   3417:     var founduname=0;
1.243     albertel 3418:     var foundID=0;
1.27      albertel 3419:     for (i=0;i<=vf.nfields.value;i++) {
                   3420:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3421:       if (i==0 && tw!=0) { foundID=1; }
                   3422:       if (i==1 && tw!=0) { founduname=1; }
                   3423:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3424:     }
1.246     albertel 3425:     if (founduname==0 && foundID==0) {
                   3426: 	alert('$error1');
                   3427: 	return;
1.27      albertel 3428:     }
                   3429:     if (foundsomething==0) {
1.246     albertel 3430: 	alert('$error2');
                   3431: 	return;
1.27      albertel 3432:     }
                   3433:     vf.submit();
                   3434:   }
                   3435:   function flip(vf,tf) {
                   3436:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3437:     var i;
                   3438:     for (i=0;i<=vf.nfields.value;i++) {
                   3439:       //can not pick the same destination field for both name and domain
                   3440:       if (((i ==0)||(i ==1)) && 
                   3441:           ((tf==0)||(tf==1)) && 
                   3442:           (i!=tf) &&
                   3443:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3444:         eval('vf.f'+i+'.selectedIndex=0;')
                   3445:       }
                   3446:     }
                   3447:   }
                   3448: ENDPICK
                   3449: }
                   3450: 
                   3451: sub csvupload_javascript_forward_associate {
1.246     albertel 3452:     my $error1=&mt('You need to specify the username or ID');
                   3453:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3454:   return(<<ENDPICK);
                   3455:   function verify(vf) {
                   3456:     var foundsomething=0;
                   3457:     var founduname=0;
1.243     albertel 3458:     var foundID=0;
1.27      albertel 3459:     for (i=0;i<=vf.nfields.value;i++) {
                   3460:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3461:       if (tw==1) { foundID=1; }
                   3462:       if (tw==2) { founduname=1; }
                   3463:       if (tw>3) { foundsomething=1; }
1.27      albertel 3464:     }
1.246     albertel 3465:     if (founduname==0 && foundID==0) {
                   3466: 	alert('$error1');
                   3467: 	return;
1.27      albertel 3468:     }
                   3469:     if (foundsomething==0) {
1.246     albertel 3470: 	alert('$error2');
                   3471: 	return;
1.27      albertel 3472:     }
                   3473:     vf.submit();
                   3474:   }
                   3475:   function flip(vf,tf) {
                   3476:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3477:     var i;
                   3478:     //can not pick the same destination field twice
                   3479:     for (i=0;i<=vf.nfields.value;i++) {
                   3480:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3481:         eval('vf.f'+i+'.selectedIndex=0;')
                   3482:       }
                   3483:     }
                   3484:   }
                   3485: ENDPICK
                   3486: }
                   3487: 
1.26      albertel 3488: sub csvuploadmap_header {
1.324     albertel 3489:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3490:     my $javascript;
1.257     albertel 3491:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3492: 	$javascript=&csvupload_javascript_reverse_associate();
                   3493:     } else {
                   3494: 	$javascript=&csvupload_javascript_forward_associate();
                   3495:     }
1.45      ng       3496: 
1.324     albertel 3497:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3498:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3499:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3500:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3501:     $request->print(<<ENDPICK);
1.26      albertel 3502: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3503: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3504: $result
1.326     albertel 3505: <hr />
1.26      albertel 3506: <h3>Identify fields</h3>
                   3507: Total number of records found in file: $distotal <hr />
                   3508: Enter as many fields as you can. The system will inform you and bring you back
                   3509: to this page if the data selected is insufficient to run your class.<hr />
                   3510: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3511: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3512: <input type="hidden" name="associate"  value="" />
                   3513: <input type="hidden" name="phase"      value="three" />
                   3514: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3515: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3516: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3517: <input type="hidden" name="upfile_associate" 
1.257     albertel 3518:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3519: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3520: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3521: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3522: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3523: <hr />
                   3524: <script type="text/javascript" language="Javascript">
                   3525: $javascript
                   3526: </script>
                   3527: ENDPICK
1.118     ng       3528:     return '';
1.26      albertel 3529: 
                   3530: }
                   3531: 
                   3532: sub csvupload_fields {
1.324     albertel 3533:     my ($symb) = @_;
                   3534:     my (@parts) = &getpartlist($symb);
1.243     albertel 3535:     my @fields=(['ID','Student ID'],
                   3536: 		['username','Student Username'],
                   3537: 		['domain','Student Domain']);
1.324     albertel 3538:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3539:     foreach my $part (sort(@parts)) {
                   3540: 	my @datum;
                   3541: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3542: 	my $name=$part;
                   3543: 	if  (!$display) { $display = $name; }
                   3544: 	@datum=($name,$display);
1.244     albertel 3545: 	if ($name=~/^stores_(.*)_awarded/) {
                   3546: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3547: 	}
1.41      ng       3548: 	push(@fields,\@datum);
                   3549:     }
                   3550:     return (@fields);
1.26      albertel 3551: }
                   3552: 
                   3553: sub csvuploadmap_footer {
1.41      ng       3554:     my ($request,$i,$keyfields) =@_;
                   3555:     $request->print(<<ENDPICK);
1.26      albertel 3556: </table>
                   3557: <input type="hidden" name="nfields" value="$i" />
                   3558: <input type="hidden" name="keyfields" value="$keyfields" />
                   3559: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3560: </form>
                   3561: ENDPICK
                   3562: }
                   3563: 
1.283     albertel 3564: sub checkforfile_js {
1.86      ng       3565:     my $result =<<CSVFORMJS;
                   3566: <script type="text/javascript" language="javascript">
                   3567:     function checkUpload(formname) {
                   3568: 	if (formname.upfile.value == "") {
                   3569: 	    alert("Please use the browse button to select a file from your local directory.");
                   3570: 	    return false;
                   3571: 	}
                   3572: 	formname.submit();
                   3573:     }
                   3574:     </script>
                   3575: CSVFORMJS
1.283     albertel 3576:     return $result;
                   3577: }
                   3578: 
                   3579: sub upcsvScores_form {
                   3580:     my ($request) = shift;
1.324     albertel 3581:     my ($symb)=&get_symb($request);
1.283     albertel 3582:     if (!$symb) {return '';}
                   3583:     my $result=&checkforfile_js();
1.257     albertel 3584:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3585:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3586:     $result.=$table;
1.326     albertel 3587:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3588:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3589:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3590: 	'.</b></td></tr>'."\n";
                   3591:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3592:     my $upload=&mt("Upload Scores");
1.86      ng       3593:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3594:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3595:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3596:     $result.=<<ENDUPFORM;
1.106     albertel 3597: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3598: <input type="hidden" name="symb" value="$symb" />
                   3599: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3600: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3601: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3602: $upfile_select
1.370     www      3603: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3604: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3605: </form>
                   3606: ENDUPFORM
1.370     www      3607:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3608:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3609:     .'</td></tr></table>'."\n";
1.86      ng       3610:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3611:     $result.=&show_grading_menu_form($symb);
1.86      ng       3612:     return $result;
                   3613: }
                   3614: 
                   3615: 
1.26      albertel 3616: sub csvuploadmap {
1.41      ng       3617:     my ($request)= @_;
1.324     albertel 3618:     my ($symb)=&get_symb($request);
1.41      ng       3619:     if (!$symb) {return '';}
1.72      ng       3620: 
1.41      ng       3621:     my $datatoken;
1.257     albertel 3622:     if (!$env{'form.datatoken'}) {
1.41      ng       3623: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3624:     } else {
1.257     albertel 3625: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3626: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3627:     }
1.41      ng       3628:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3629:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3630:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3631:     my ($i,$keyfields);
                   3632:     if (@records) {
1.324     albertel 3633: 	my @fields=&csvupload_fields($symb);
1.45      ng       3634: 
1.257     albertel 3635: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3636: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3637: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3638: 							  \@fields);
                   3639: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3640: 	    chop($keyfields);
                   3641: 	} else {
                   3642: 	    unshift(@fields,['none','']);
                   3643: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3644: 							    \@fields);
1.311     banghart 3645:             foreach my $rec (@records) {
                   3646:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3647:                 if (%temp) {
                   3648:                     $keyfields=join(',',sort(keys(%temp)));
                   3649:                     last;
                   3650:                 }
                   3651:             }
1.41      ng       3652: 	}
                   3653:     }
                   3654:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3655:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3656: 
1.41      ng       3657:     return '';
1.27      albertel 3658: }
                   3659: 
1.246     albertel 3660: sub csvuploadoptions {
1.41      ng       3661:     my ($request)= @_;
1.324     albertel 3662:     my ($symb)=&get_symb($request);
1.257     albertel 3663:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3664:     my $ignore=&mt('Ignore First Line');
                   3665:     $request->print(<<ENDPICK);
                   3666: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3667: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3668: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3669: <!--
1.246     albertel 3670: <p>
                   3671: <label>
                   3672:    <input type="checkbox" name="show_full_results" />
                   3673:    Show a table of all changes
                   3674: </label>
                   3675: </p>
1.302     albertel 3676: -->
1.246     albertel 3677: <p>
                   3678: <label>
                   3679:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3680:    Overwrite any existing score
                   3681: </label>
                   3682: </p>
                   3683: ENDPICK
                   3684:     my %fields=&get_fields();
                   3685:     if (!defined($fields{'domain'})) {
1.257     albertel 3686: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3687: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3688:     }
1.257     albertel 3689:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3690: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3691: 	my $cleankey=$1;
                   3692: 	if ($cleankey eq 'command') { next; }
                   3693: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3694: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3695:     }
                   3696:     # FIXME do a check for any duplicated user ids...
                   3697:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3698:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3699: <hr /></form>'."\n");
1.324     albertel 3700:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3701:     return '';
                   3702: }
                   3703: 
                   3704: sub get_fields {
                   3705:     my %fields;
1.257     albertel 3706:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3707:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3708: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3709: 	    if ($env{'form.f'.$i} ne 'none') {
                   3710: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3711: 	    }
                   3712: 	} else {
1.257     albertel 3713: 	    if ($env{'form.f'.$i} ne 'none') {
                   3714: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3715: 	    }
                   3716: 	}
1.27      albertel 3717:     }
1.246     albertel 3718:     return %fields;
                   3719: }
                   3720: 
                   3721: sub csvuploadassign {
                   3722:     my ($request)= @_;
1.324     albertel 3723:     my ($symb)=&get_symb($request);
1.246     albertel 3724:     if (!$symb) {return '';}
1.345     bowersj2 3725:     my $error_msg = '';
1.246     albertel 3726:     &Apache::loncommon::load_tmp_file($request);
                   3727:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3728:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3729:     my %fields=&get_fields();
1.41      ng       3730:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3731:     my $courseid=$env{'request.course.id'};
1.97      albertel 3732:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3733:     my @notallowed;
1.41      ng       3734:     my @skipped;
                   3735:     my $countdone=0;
                   3736:     foreach my $grade (@gradedata) {
                   3737: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3738: 	my $domain;
                   3739: 	if ($entries{$fields{'domain'}}) {
                   3740: 	    $domain=$entries{$fields{'domain'}};
                   3741: 	} else {
1.257     albertel 3742: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3743: 	}
1.243     albertel 3744: 	$domain=~s/\s//g;
1.41      ng       3745: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3746: 	$username=~s/\s//g;
1.243     albertel 3747: 	if (!$username) {
                   3748: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3749: 	    $id=~s/\s//g;
1.243     albertel 3750: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3751: 	    $username=$ids{$id};
                   3752: 	}
1.41      ng       3753: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3754: 	    my $id=$entries{$fields{'ID'}};
                   3755: 	    $id=~s/\s//g;
                   3756: 	    if ($id) {
                   3757: 		push(@skipped,"$id:$domain");
                   3758: 	    } else {
                   3759: 		push(@skipped,"$username:$domain");
                   3760: 	    }
1.41      ng       3761: 	    next;
                   3762: 	}
1.108     albertel 3763: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3764: 	if (!&canmodify($usec)) {
                   3765: 	    push(@notallowed,"$username:$domain");
                   3766: 	    next;
                   3767: 	}
1.244     albertel 3768: 	my %points;
1.41      ng       3769: 	my %grades;
                   3770: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3771: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3772: 		$dest eq 'domain') { next; }
                   3773: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3774: 	    if ($dest=~/stores_(.*)_points/) {
                   3775: 		my $part=$1;
                   3776: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3777: 					      $symb,$domain,$username);
1.345     bowersj2 3778:                 if ($wgt) {
                   3779:                     $entries{$fields{$dest}}=~s/\s//g;
                   3780:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3781:                     my $award='correct_by_override';
                   3782:                     $grades{"resource.$part.awarded"}=$pcr;
                   3783:                     $grades{"resource.$part.solved"}=$award;
                   3784:                     $points{$part}=1;
                   3785:                 } else {
                   3786:                     $error_msg = "<br />" .
                   3787:                         &mt("Some point values were assigned"
                   3788:                             ." for problems with a weight "
                   3789:                             ."of zero. These values were "
                   3790:                             ."ignored.");
                   3791:                 }
1.244     albertel 3792: 	    } else {
                   3793: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3794: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3795: 		my $store_key=$dest;
                   3796: 		$store_key=~s/^stores/resource/;
                   3797: 		$store_key=~s/_/\./g;
                   3798: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3799: 	    }
1.41      ng       3800: 	}
1.398     albertel 3801: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3802: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.244     albertel 3803: #	&Apache::lonnet::logthis(" storing ".(join('-',%grades)));
1.302     albertel 3804: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3805: 					   $env{'request.course.id'},
                   3806: 					   $domain,$username);
                   3807: 	if ($result eq 'ok') {
                   3808: 	    $request->print('.');
                   3809: 	} else {
                   3810: 	    $request->print("<p>
1.398     albertel 3811:                               <span class=\"LC_error\">
                   3812:                                  Failed to save student $username:$domain.
                   3813:                                  Message when trying to save was ($result)
                   3814:                               </span>
1.302     albertel 3815:                              </p>" );
                   3816: 	}
1.41      ng       3817: 	$request->rflush();
                   3818: 	$countdone++;
                   3819:     }
1.398     albertel 3820:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3821:     if (@skipped) {
1.398     albertel 3822: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3823: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3824:     }
                   3825:     if (@notallowed) {
1.398     albertel 3826: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3827: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3828:     }
1.106     albertel 3829:     $request->print("<br />\n");
1.324     albertel 3830:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3831:     return $error_msg;
1.26      albertel 3832: }
1.44      ng       3833: #------------- end of section for handling csv file upload ---------
                   3834: #
                   3835: #-------------------------------------------------------------------
                   3836: #
1.122     ng       3837: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3838: #
                   3839: #--- Select a page/sequence and a student to grade
1.68      ng       3840: sub pickStudentPage {
                   3841:     my ($request) = shift;
                   3842: 
                   3843:     $request->print(<<LISTJAVASCRIPT);
                   3844: <script type="text/javascript" language="javascript">
                   3845: 
                   3846: function checkPickOne(formname) {
1.76      ng       3847:     if (radioSelection(formname.student) == null) {
1.68      ng       3848: 	alert("Please select the student you wish to grade.");
                   3849: 	return;
                   3850:     }
1.125     ng       3851:     ptr = pullDownSelection(formname.selectpage);
                   3852:     formname.page.value = formname["page"+ptr].value;
                   3853:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3854:     formname.submit();
                   3855: }
                   3856: 
                   3857: </script>
                   3858: LISTJAVASCRIPT
1.118     ng       3859:     &commonJSfunctions($request);
1.324     albertel 3860:     my ($symb) = &get_symb($request);
1.257     albertel 3861:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3862:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3863:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3864: 
1.398     albertel 3865:     my $result='<h3><span class="LC_info">&nbsp;'.
                   3866: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       3867: 
1.80      ng       3868:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3869:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 3870:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 3871:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3872: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3873: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3874:     my $ctr=0;
1.68      ng       3875:     foreach (@$titles) {
                   3876: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3877: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 3878: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       3879: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3880: 	$ctr++;
1.68      ng       3881:     }
1.326     albertel 3882:     $result.= '</select>'."<br />\n";
1.70      ng       3883:     $ctr=0;
                   3884:     foreach (@$titles) {
                   3885: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3886: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3887: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3888: 	$ctr++;
                   3889:     }
1.72      ng       3890:     $result.='<input type="hidden" name="page" />'."\n".
                   3891: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3892: 
1.401     albertel 3893:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 3894: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       3895: 
1.71      ng       3896:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 3897: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 3898: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 3899: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.72      ng       3900: 
1.68      ng       3901:     $result.='<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
1.257     albertel 3902: 	'<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.72      ng       3903: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 3904: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 3905: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       3906: 
1.382     albertel 3907:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   3908: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   3909: 
1.80      ng       3910:     $result.='&nbsp;<input type="button" '.
1.126     ng       3911: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       3912: 
1.68      ng       3913:     $request->print($result);
                   3914: 
1.326     albertel 3915:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       3916: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3917: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       3918: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3919: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       3920: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3921: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       3922:  
1.76      ng       3923:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       3924:     my $ptr = 1;
1.294     albertel 3925:     foreach my $student (sort 
                   3926: 			 {
                   3927: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3928: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3929: 			     }
                   3930: 			     return $a cmp $b;
                   3931: 			 } (keys(%$fullname))) {
1.68      ng       3932: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       3933: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   3934: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 3935: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   3936: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       3937: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       3938: 	$ptr++;
                   3939:     }
1.381     albertel 3940:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   3941:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       3942:     $studentTable.='<input type="button" '.
                   3943: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       3944: 
1.324     albertel 3945:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       3946:     $request->print($studentTable);
                   3947: 
                   3948:     return '';
                   3949: }
                   3950: 
                   3951: sub getSymbMap {
1.132     bowersj2 3952:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       3953: 
                   3954:     my %symbx = ();
                   3955:     my @titles = ();
1.117     bowersj2 3956:     my $minder = 0;
                   3957: 
                   3958:     # Gather every sequence that has problems.
1.240     albertel 3959:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   3960: 					       1,0,1);
1.117     bowersj2 3961:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 3962: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 3963: 	    my $title = $minder.'.'.
                   3964: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   3965: 	    push(@titles, $title); # minder in case two titles are identical
                   3966: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 3967: 	    $minder++;
1.241     albertel 3968: 	}
1.68      ng       3969:     }
                   3970:     return \@titles,\%symbx;
                   3971: }
                   3972: 
1.72      ng       3973: #
                   3974: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       3975: sub displayPage {
                   3976:     my ($request) = shift;
                   3977: 
1.324     albertel 3978:     my ($symb) = &get_symb($request);
1.257     albertel 3979:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3980:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3981:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3982:     my $pageTitle = $env{'form.page'};
1.103     albertel 3983:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 3984:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   3985:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 3986: 
                   3987:     #need to make sure we have the correct data for later EXT calls, 
                   3988:     #thus invalidate the cache
                   3989:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3990:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3991:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3992:     &Apache::lonnet::clear_EXT_cache_status();
                   3993: 
1.103     albertel 3994:     if (!&canview($usec)) {
1.398     albertel 3995: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 3996: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 3997: 	return;
                   3998:     }
1.398     albertel 3999:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4000:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       4001: 	'</h3>'."\n";
1.382     albertel 4002:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4003: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   4004:     } else {
                   4005: 	delete($env{'form.CODE'});
                   4006:     }
1.71      ng       4007:     &sub_page_js($request);
                   4008:     $request->print($result);
                   4009: 
1.132     bowersj2 4010:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4011:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4012:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4013:     if (!$map) {
1.398     albertel 4014: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4015: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4016: 	return; 
                   4017:     }
1.68      ng       4018:     my $iterator = $navmap->getIterator($map->map_start(),
                   4019: 					$map->map_finish());
                   4020: 
1.71      ng       4021:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4022: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4023: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4024: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4025: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4026: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4027: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4028: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4029: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4030: 
1.382     albertel 4031:     if (defined($env{'form.CODE'})) {
                   4032: 	$studentTable.=
                   4033: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4034:     }
1.381     albertel 4035:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4036: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4037: 	'/check.gif" height="16" border="0" />';
                   4038: 
1.118     ng       4039:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4040: 	' symbol.'."\n".
1.71      ng       4041: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4042: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4043: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4044: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4045: 
1.329     albertel 4046:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4047:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4048:     $iterator->next(); # skip the first BEGIN_MAP
                   4049:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4050:     while ($depth > 0) {
1.68      ng       4051:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4052:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4053: 
1.385     albertel 4054:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4055: 	    my $parts = $curRes->parts();
1.68      ng       4056:             my $title = $curRes->compTitle();
1.71      ng       4057: 	    my $symbx = $curRes->symb();
1.196     albertel 4058: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4059: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4060: 	    $studentTable.='<td valign="top">';
1.382     albertel 4061: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4062: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4063: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4064: 					     undef,'both',\%form);
1.71      ng       4065: 	    } else {
1.382     albertel 4066: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4067: 		$companswer =~ s|<form(.*?)>||g;
                   4068: 		$companswer =~ s|</form>||g;
1.71      ng       4069: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4070: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4071: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4072: #		}
1.116     ng       4073: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4074: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4075: 	    }
                   4076: 
1.257     albertel 4077: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4078: 
1.257     albertel 4079: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4080: 		if ($record{'version'} eq '') {
1.398     albertel 4081: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4082: 		} else {
1.116     ng       4083: 		    my %responseType = ();
                   4084: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4085: 			my @responseIds =$curRes->responseIds($partid);
                   4086: 			my @responseType =$curRes->responseType($partid);
                   4087: 			my %responseIds;
                   4088: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4089: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4090: 			}
                   4091: 			$responseType{$partid} = \%responseIds;
1.116     ng       4092: 		    }
1.148     albertel 4093: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4094: 
1.71      ng       4095: 		}
1.257     albertel 4096: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4097: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4098: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4099: 									$env{'request.course.id'},
1.71      ng       4100: 									'','.submission');
                   4101:  
                   4102: 	    }
1.103     albertel 4103: 	    if (&canmodify($usec)) {
                   4104: 		foreach my $partid (@{$parts}) {
                   4105: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4106: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4107: 		    $question++;
                   4108: 		}
1.196     albertel 4109: 		$prob++;
1.71      ng       4110: 	    }
                   4111: 	    $studentTable.='</td></tr>';
1.68      ng       4112: 
1.103     albertel 4113: 	}
1.68      ng       4114:         $curRes = $iterator->next();
                   4115:     }
                   4116: 
1.381     albertel 4117:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4118: 	'<input type="button" value="Save" '.
1.381     albertel 4119: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4120: 	'</form>'."\n";
1.324     albertel 4121:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4122:     $request->print($studentTable);
                   4123: 
                   4124:     return '';
1.119     ng       4125: }
                   4126: 
                   4127: sub displaySubByDates {
1.148     albertel 4128:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4129:     my $isCODE=0;
1.335     albertel 4130:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4131:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4132:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4133: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4134: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4135: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4136: 	'<td><b>Submission</b></td>'.
                   4137: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4138:     my ($version);
                   4139:     my %mark;
1.148     albertel 4140:     my %orders;
1.119     ng       4141:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4142:     if (!exists($$record{'1:timestamp'})) {
1.398     albertel 4143: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
1.147     albertel 4144:     }
1.335     albertel 4145: 
                   4146:     my $interaction;
1.119     ng       4147:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4148: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4149: 	if (exists($$record{$version.':resource.0.version'})) {
                   4150: 	    $interaction = $$record{$version.':resource.0.version'};
                   4151: 	}
                   4152: 
                   4153: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4154: 		             : "$version:resource");
                   4155: 	#&Apache::lonnet::logthis(" got $where");
1.119     ng       4156: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4157: 	if ($isCODE) {
                   4158: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4159: 	}
1.119     ng       4160: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4161: 	my @displaySub = ();
                   4162: 	foreach my $partid (@{$parts}) {
1.335     albertel 4163: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4164: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4165: 	    
                   4166: 
1.122     ng       4167: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4168: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4169: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4170: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4171: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4172: 
                   4173: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4174: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   4175: 		    #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
1.207     albertel 4176: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.398     albertel 4177: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
                   4178: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4179: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4180: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4181: 		    } else {
                   4182: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4183: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4184: 		    }
1.335     albertel 4185: 		    my $responseType=($isTask ? 'Task'
                   4186:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4187: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4188: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4189: 			$orders{$partid}->{$responseId}=
                   4190: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4191: 		    }
1.147     albertel 4192: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4193: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4194: 		}
                   4195: 	    }
1.335     albertel 4196: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4197: 		$displaySub[1].='Checked in by '.
                   4198: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4199: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4200: 		    '<br />';
                   4201: 	    }
                   4202: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4203: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4204: 		    lc($$record{"$where.$partid.award"}).' '.
                   4205: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4206: 		    '<br />';
                   4207: 	    }
1.335     albertel 4208: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4209: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4210: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4211: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4212: 		$displaySub[2].=
                   4213: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4214: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4215: 	    }
                   4216: 	}
                   4217: 	# needed because old essay regrader has not parts info
                   4218: 	if (exists $$record{"$version:resource.regrader"}) {
                   4219: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4220: 	}
                   4221: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4222: 	if ($displaySub[2]) {
                   4223: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4224: 	}
1.382     albertel 4225: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4226:     
1.119     ng       4227:     }
                   4228:     $studentTable.='</table></td></tr></table>';
                   4229:     return $studentTable;
1.71      ng       4230: }
                   4231: 
                   4232: sub updateGradeByPage {
                   4233:     my ($request) = shift;
                   4234: 
1.257     albertel 4235:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4236:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4237:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4238:     my $pageTitle = $env{'form.page'};
1.103     albertel 4239:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4240:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4241:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4242:     if (!&canmodify($usec)) {
1.398     albertel 4243: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4244: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4245: 	return;
                   4246:     }
1.398     albertel 4247:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4248:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4249: 	'</h3>'."\n";
1.70      ng       4250: 
1.68      ng       4251:     $request->print($result);
                   4252: 
1.132     bowersj2 4253:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4254:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4255:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4256:     if (!$map) {
1.398     albertel 4257: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4258: 	my ($symb)=&get_symb($request);
                   4259: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4260: 	return; 
                   4261:     }
1.71      ng       4262:     my $iterator = $navmap->getIterator($map->map_start(),
                   4263: 					$map->map_finish());
1.70      ng       4264: 
1.71      ng       4265:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4266: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4267: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4268: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4269: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4270: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4271: 
                   4272:     $iterator->next(); # skip the first BEGIN_MAP
                   4273:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4274:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4275:     while ($depth > 0) {
1.71      ng       4276:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4277:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4278: 
1.385     albertel 4279:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4280: 	    my $parts = $curRes->parts();
1.71      ng       4281:             my $title = $curRes->compTitle();
                   4282: 	    my $symbx = $curRes->symb();
1.196     albertel 4283: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4284: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4285: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4286: 
                   4287: 	    my %newrecord=();
                   4288: 	    my @displayPts=();
1.269     raeburn  4289:             my %aggregate = ();
                   4290:             my $aggregateflag = 0;
1.71      ng       4291: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4292: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4293: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4294: 
1.257     albertel 4295: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4296: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4297: 		my $partial = $newpts/$wgt;
                   4298: 		my $score;
                   4299: 		if ($partial > 0) {
                   4300: 		    $score = 'correct_by_override';
1.125     ng       4301: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4302: 		    $score = 'incorrect_by_override';
                   4303: 		}
1.257     albertel 4304: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4305: 		if ($dropMenu eq 'excused') {
1.71      ng       4306: 		    $partial = '';
                   4307: 		    $score = 'excused';
1.125     ng       4308: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4309: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4310: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4311: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4312: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4313: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4314: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4315: 		    $changeflag++;
                   4316: 		    $newpts = '';
1.269     raeburn  4317:                     
                   4318:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4319:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4320:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4321:                     if ($aggtries > 0) {
                   4322:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4323:                         $aggregateflag = 1;
                   4324:                     }
1.71      ng       4325: 		}
1.324     albertel 4326: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4327: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4328: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4329: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4330: 		    '&nbsp;<br />';
1.207     albertel 4331: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4332: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4333: 		    '&nbsp;<br />';
1.71      ng       4334: 		$question++;
1.380     albertel 4335: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4336: 
1.71      ng       4337: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4338: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4339: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4340: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4341: 
                   4342: 		$changeflag++;
                   4343: 	    }
                   4344: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4345: 		my %record = 
                   4346: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4347: 					     $udom,$uname);
                   4348: 
                   4349: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4350: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4351: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4352: 		    $newrecord{'resource.CODE'} = '';
                   4353: 		}
1.257     albertel 4354: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4355: 					$udom,$uname);
1.382     albertel 4356: 		%record = &Apache::lonnet::restore($symbx,
                   4357: 						   $env{'request.course.id'},
                   4358: 						   $udom,$uname);
1.380     albertel 4359: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4360: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4361: 	    }
1.380     albertel 4362: 	    
1.269     raeburn  4363:             if ($aggregateflag) {
                   4364:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4365:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4366:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4367:             }
1.125     ng       4368: 
1.71      ng       4369: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4370: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4371: 		'</tr>';
1.68      ng       4372: 
1.196     albertel 4373: 	    $prob++;
1.68      ng       4374: 	}
1.71      ng       4375:         $curRes = $iterator->next();
1.68      ng       4376:     }
1.98      albertel 4377: 
1.71      ng       4378:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4379:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4380:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4381: 		  'The scores were changed for '.
                   4382: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4383:     $request->print($grademsg.$studentTable);
1.68      ng       4384: 
1.70      ng       4385:     return '';
                   4386: }
                   4387: 
1.72      ng       4388: #-------- end of section for handling grading by page/sequence ---------
                   4389: #
                   4390: #-------------------------------------------------------------------
                   4391: 
1.75      albertel 4392: #--------------------Scantron Grading-----------------------------------
                   4393: #
                   4394: #------ start of section for handling grading by page/sequence ---------
                   4395: 
1.423     albertel 4396: =pod
                   4397: 
                   4398: =head1 Bubble sheet grading routines
                   4399: 
1.424     albertel 4400:   For this documentation:
                   4401: 
                   4402:    'scanline' refers to the full line of characters
                   4403:    from the file that we are parsing that represents one entire sheet
                   4404: 
                   4405:    'bubble line' refers to the data
                   4406:    representing the line of bubbles that are on the physical bubble sheet
                   4407: 
                   4408: 
                   4409: The overall process is that a scanned in bubble sheet data is uploaded
                   4410: into a course. When a user wants to grade, they select a
                   4411: sequence/folder of resources, a file of bubble sheet info, and pick
                   4412: one of the predefined configurations for what each scanline looks
                   4413: like.
                   4414: 
                   4415: Next each scanline is checked for any errors of either 'missing
                   4416: bubbles' (it's an error because it may have been missed scanned
                   4417: because too light bubbling), 'double bubble' (each bubble line should
                   4418: have no more that one letter picked), invalid or duplicated CODE,
                   4419: invalid student ID
                   4420: 
                   4421: If the CODE option is used that determines the randomization of the
                   4422: homework problems, either way the student ID is looked up into a
                   4423: username:domain.
                   4424: 
                   4425: During the validation phase the instructor can choose to skip scanlines. 
                   4426: 
                   4427: After the validation phase, there is now 3 bubble sheet files
                   4428: 
                   4429:   scantron_original_filename (unmodified original file)
                   4430:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4431:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4432: 
                   4433: Also there is a separate hash nohist_scantrondata that contains extra
                   4434: correction information that isn't representable in the bubble sheet
                   4435: file (see &scantron_getfile() for more information)
                   4436: 
                   4437: After all scanlines are either valid, marked as valid or skipped, then
                   4438: foreach line foreach problem in the picked sequence, an ssi request is
                   4439: made that simulates a user submitting their selected letter(s) against
                   4440: the homework problem.
1.423     albertel 4441: 
                   4442: =over 4
                   4443: 
                   4444: =cut
                   4445: 
                   4446: 
                   4447: =pod 
                   4448: 
                   4449: =item defaultFormData
                   4450: 
                   4451:   Returns html hidden inputs used to hold context/default values.
                   4452: 
                   4453:  Arguments:
                   4454:   $symb - $symb of the current resource 
                   4455: 
                   4456: =cut
1.422     foxr     4457: 
1.81      albertel 4458: sub defaultFormData {
1.324     albertel 4459:     my ($symb)=@_;
1.81      albertel 4460:     return '
1.418     albertel 4461:       <input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4462:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4463:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4464: }
                   4465: 
1.423     albertel 4466: =pod 
                   4467: 
                   4468: =item getSequenceDropDown
                   4469: 
                   4470:    Return html dropdown of possible sequences to grade
                   4471:  
                   4472:  Arguments:
                   4473:    $symb - $symb of the current resource 
                   4474: 
                   4475: =cut
1.422     foxr     4476: 
1.75      albertel 4477: sub getSequenceDropDown {
1.423     albertel 4478:     my ($symb)=@_;
1.75      albertel 4479:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4480:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4481:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4482:     my $ctr=0;
                   4483:     foreach (@$titles) {
                   4484: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4485: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4486: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4487: 	    '>'.$showtitle.'</option>'."\n";
                   4488: 	$ctr++;
                   4489:     }
                   4490:     $result.= '</select>';
                   4491:     return $result;
                   4492: }
                   4493: 
1.423     albertel 4494: 
                   4495: =pod 
                   4496: 
                   4497: =item scantron_filenames
                   4498: 
                   4499:    Returns a list of the scantron files in the current course 
                   4500: 
                   4501: =cut
1.422     foxr     4502: 
1.202     albertel 4503: sub scantron_filenames {
1.257     albertel 4504:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4505:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4506:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4507: 				    &propath($cdom,$cname));
1.202     albertel 4508:     my @possiblenames;
1.201     albertel 4509:     foreach my $filename (sort(@files)) {
1.157     albertel 4510: 	($filename)=split(/&/,$filename);
                   4511: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4512: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4513: 	push(@possiblenames,$filename);
                   4514:     }
                   4515:     return @possiblenames;
                   4516: }
                   4517: 
1.423     albertel 4518: =pod 
                   4519: 
                   4520: =item scantron_uploads
                   4521: 
                   4522:    Returns  html drop-down list of scantron files in current course.
                   4523: 
                   4524:  Arguments:
                   4525:    $file2grade - filename to set as selected in the dropdown
                   4526: 
                   4527: =cut
1.422     foxr     4528: 
1.202     albertel 4529: sub scantron_uploads {
1.209     ng       4530:     my ($file2grade) = @_;
1.202     albertel 4531:     my $result=	'<select name="scantron_selectfile">';
                   4532:     $result.="<option></option>";
                   4533:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4534: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4535:     }
                   4536:     $result.="</select>";
                   4537:     return $result;
                   4538: }
                   4539: 
1.423     albertel 4540: =pod 
                   4541: 
                   4542: =item scantron_scantab
                   4543: 
                   4544:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4545:   file.
                   4546: 
                   4547: =cut
1.422     foxr     4548: 
1.82      albertel 4549: sub scantron_scantab {
                   4550:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4551:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4552:     $result.='<option></option>'."\n";
1.82      albertel 4553:     foreach my $line (<$fh>) {
                   4554: 	my ($name,$descrip)=split(/:/,$line);
                   4555: 	if ($name =~ /^\#/) { next; }
                   4556: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4557:     }
                   4558:     $result.='</select>'."\n";
                   4559: 
                   4560:     return $result;
                   4561: }
                   4562: 
1.423     albertel 4563: =pod 
                   4564: 
                   4565: =item scantron_CODElist
                   4566: 
                   4567:   Returns html drop down of the saved CODE lists from current course,
                   4568:   generated from earlier printings.
                   4569: 
                   4570: =cut
1.422     foxr     4571: 
1.186     albertel 4572: sub scantron_CODElist {
1.257     albertel 4573:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4574:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4575:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4576:     my $namechoice='<option></option>';
1.225     albertel 4577:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4578: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4579: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4580: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4581:     }
                   4582:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4583:     return $namechoice;
                   4584: }
                   4585: 
1.423     albertel 4586: =pod 
                   4587: 
                   4588: =item scantron_CODEunique
                   4589: 
                   4590:   Returns the html for "Each CODE to be used once" radio.
                   4591: 
                   4592: =cut
1.422     foxr     4593: 
1.186     albertel 4594: sub scantron_CODEunique {
1.381     albertel 4595:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4596:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4597:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4598:                 </span>
                   4599:                 <span style="white-space: nowrap;">
1.272     albertel 4600:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4601:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4602:                 </span>';
1.186     albertel 4603:     return $result;
                   4604: }
1.423     albertel 4605: 
                   4606: =pod 
                   4607: 
                   4608: =item scantron_selectphase
                   4609: 
                   4610:   Generates the initial screen to start the bubble sheet process.
                   4611:   Allows for - starting a grading run.
1.424     albertel 4612:              - downloading existing scan data (original, corrected
1.423     albertel 4613:                                                 or skipped info)
                   4614: 
                   4615:              - uploading new scan data
                   4616: 
                   4617:  Arguments:
                   4618:   $r          - The Apache request object
                   4619:   $file2grade - name of the file that contain the scanned data to score
                   4620: 
                   4621: =cut
1.186     albertel 4622: 
1.75      albertel 4623: sub scantron_selectphase {
1.209     ng       4624:     my ($r,$file2grade) = @_;
1.324     albertel 4625:     my ($symb)=&get_symb($r);
1.75      albertel 4626:     if (!$symb) {return '';}
1.423     albertel 4627:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4628:     my $default_form_data=&defaultFormData($symb);
                   4629:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4630:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4631:     my $format_selector=&scantron_scantab();
1.186     albertel 4632:     my $CODE_selector=&scantron_CODElist();
                   4633:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4634:     my $result;
1.422     foxr     4635: 
                   4636:     # Chunk of form to prompt for a file to grade and how:
                   4637: 
1.75      albertel 4638:     $result.= <<SCANTRONFORM;
1.162     albertel 4639:     <table width="100%" border="0">
1.75      albertel 4640:     <tr>
1.226     albertel 4641:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4642:       <td bgcolor="#777777">
1.203     albertel 4643:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4644:         $default_form_data
1.75      albertel 4645:         <table width="100%" border="0">
                   4646:           <tr bgcolor="#e6ffff">
1.174     albertel 4647:             <td colspan="2">
                   4648:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4649:             </td>
                   4650:           </tr>
                   4651:           <tr bgcolor="#ffffe6">
1.174     albertel 4652:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4653:           </tr>
                   4654:           <tr bgcolor="#ffffe6">
1.174     albertel 4655:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4656:           </tr>
1.82      albertel 4657:           <tr bgcolor="#ffffe6">
1.174     albertel 4658:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4659:           </tr>
1.157     albertel 4660:           <tr bgcolor="#ffffe6">
1.186     albertel 4661:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4662:           </tr>
                   4663:           <tr bgcolor="#ffffe6">
                   4664:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4665:           </tr>
                   4666:           <tr bgcolor="#ffffe6">
1.187     albertel 4667: 	    <td> Options: </td>
                   4668:             <td>
1.272     albertel 4669: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4670:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4671:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4672: 	    </td>
                   4673:           </tr>
                   4674:           <tr bgcolor="#ffffe6">
1.174     albertel 4675:             <td colspan="2">
1.265     www      4676:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4677:             </td>
                   4678:           </tr>
                   4679:         </table>
1.226     albertel 4680:        </td>
                   4681:      </form>
1.162     albertel 4682:     </tr>
                   4683: SCANTRONFORM
                   4684:    
                   4685:     $r->print($result);
                   4686: 
1.257     albertel 4687:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4688:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4689: 
1.422     foxr     4690: 	# Chunk of form to prompt for a scantron file upload.
                   4691: 
1.162     albertel 4692:         $r->print(<<SCANTRONFORM);
                   4693:     <tr>
                   4694:       <td bgcolor="#777777">
                   4695:         <table width="100%" border="0">
                   4696:           <tr bgcolor="#e6ffff">
                   4697:             <td>
1.174     albertel 4698:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4699:             </td>
                   4700:           </tr>
                   4701:           <tr bgcolor="#ffffe6">
                   4702:             <td>
                   4703: SCANTRONFORM
1.324     albertel 4704:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4705:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4706:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4707:     $r->print(<<UPLOAD);
                   4708:               <script type="text/javascript" language="javascript">
                   4709:     function checkUpload(formname) {
                   4710: 	if (formname.upfile.value == "") {
                   4711: 	    alert("Please use the browse button to select a file from your local directory.");
                   4712: 	    return false;
                   4713: 	}
                   4714: 	formname.submit();
                   4715:     }
                   4716:               </script>
                   4717: 
                   4718:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4719:                 $default_form_data
                   4720:                 <input name='courseid' type='hidden' value='$cnum' />
                   4721:                 <input name='domainid' type='hidden' value='$cdom' />
                   4722:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4723:                 File to upload:<input type="file" name="upfile" size="50" />
                   4724:                 <br />
                   4725:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4726:               </form>
                   4727: UPLOAD
1.162     albertel 4728: 
                   4729:         $r->print(<<SCANTRONFORM);
                   4730:             </td>
                   4731:           </tr>
1.75      albertel 4732:         </table>
                   4733:       </td>
                   4734:     </tr>
1.162     albertel 4735: SCANTRONFORM
                   4736:     }
1.422     foxr     4737: 
                   4738:     # Chunk of the form that prompts to view a scoring office file,
                   4739:     # corrected file, skipped records in a file.
                   4740: 
1.187     albertel 4741:     $r->print(<<SCANTRONFORM);
                   4742:     <tr>
1.226     albertel 4743:       <form action='/adm/grades' name='scantron_download'>
                   4744:         <td bgcolor="#777777">
1.379     albertel 4745: 	  $default_form_data
1.187     albertel 4746:           <input type="hidden" name="command" value="scantron_download" />
                   4747:           <table width="100%" border="0">
                   4748:             <tr bgcolor="#e6ffff">
                   4749:               <td colspan="2">
                   4750:                 &nbsp;<b>Download a scoring office file</b>
                   4751:               </td>
                   4752:             </tr>
                   4753:             <tr bgcolor="#ffffe6">
                   4754:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4755:             </tr>
                   4756:             <tr bgcolor="#ffffe6">
                   4757:               <td colspan="2">
1.293     www      4758:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4759:               </td>
                   4760:             </tr>
                   4761:           </table>
1.226     albertel 4762:         </td>
                   4763:       </form>
1.187     albertel 4764:     </tr>
                   4765: SCANTRONFORM
1.162     albertel 4766: 
                   4767:     $r->print(<<SCANTRONFORM);
1.75      albertel 4768:   </table>
1.81      albertel 4769: $grading_menu_button
1.75      albertel 4770: SCANTRONFORM
                   4771: 
1.162     albertel 4772:     return
1.75      albertel 4773: }
                   4774: 
1.423     albertel 4775: =pod
                   4776: 
                   4777: =item get_scantron_config
                   4778: 
                   4779:    Parse and return the scantron configuration line selected as a
                   4780:    hash of configuration file fields.
                   4781: 
                   4782:  Arguments:
                   4783:     which - the name of the configuration to parse from the file.
                   4784: 
                   4785: 
                   4786:  Returns:
                   4787:             If the named configuration is not in the file, an empty
                   4788:             hash is returned.
                   4789:     a hash with the fields
                   4790:       name         - internal name for the this configuration setup
                   4791:       description  - text to display to operator that describes this config
                   4792:       CODElocation - if 0 or the string 'none'
                   4793:                           - no CODE exists for this config
                   4794:                      if -1 || the string 'letter'
                   4795:                           - a CODE exists for this config and is
                   4796:                             a string of letters
                   4797:                      Unsupported value (but planned for future support)
                   4798:                           if a positive integer
                   4799:                                - The CODE exists as the first n items from
                   4800:                                  the question section of the form
                   4801:                           if the string 'number'
                   4802:                                - The CODE exists for this config and is
                   4803:                                  a string of numbers
                   4804:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4805:                      the CODE starts
                   4806:       CODElength  - length of the CODE
                   4807:       IDstart     - column where the student ID number starts
                   4808:       IDlength    - length of the student ID info
                   4809:       Qstart      - column where the information from the bubbled
                   4810:                     'questions' start
                   4811:       Qlength     - number of columns comprising a single bubble line from
                   4812:                     the sheet. (usually either 1 or 10)
1.424     albertel 4813:       Qon         - either a single character representing the character used
1.423     albertel 4814:                     to signal a bubble was chosen in the positional setup, or
                   4815:                     the string 'letter' if the letter of the chosen bubble is
                   4816:                     in the final, or 'number' if a number representing the
                   4817:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 4818:       Qoff        - the character used to represent that a bubble was
                   4819:                     left blank
1.423     albertel 4820:       PaperID     - if the scanning process generates a unique number for each
                   4821:                     sheet scanned the column that this ID number starts in
                   4822:       PaperIDlength - number of columns that comprise the unique ID number
                   4823:                       for the sheet of paper
1.424     albertel 4824:       FirstName   - column that the first name starts in
1.423     albertel 4825:       FirstNameLength - number of columns that the first name spans
                   4826:  
                   4827:       LastName    - column that the last name starts in
                   4828:       LastNameLength - number of columns that the last name spans
                   4829: 
                   4830: =cut
1.422     foxr     4831: 
1.82      albertel 4832: sub get_scantron_config {
                   4833:     my ($which) = @_;
                   4834:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4835:     my %config;
1.157     albertel 4836:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4837:     foreach my $line (<$fh>) {
                   4838: 	my ($name,$descrip)=split(/:/,$line);
                   4839: 	if ($name ne $which ) { next; }
                   4840: 	chomp($line);
                   4841: 	my @config=split(/:/,$line);
                   4842: 	$config{'name'}=$config[0];
                   4843: 	$config{'description'}=$config[1];
                   4844: 	$config{'CODElocation'}=$config[2];
                   4845: 	$config{'CODEstart'}=$config[3];
                   4846: 	$config{'CODElength'}=$config[4];
                   4847: 	$config{'IDstart'}=$config[5];
                   4848: 	$config{'IDlength'}=$config[6];
                   4849: 	$config{'Qstart'}=$config[7];
                   4850: 	$config{'Qlength'}=$config[8];
                   4851: 	$config{'Qoff'}=$config[9];
                   4852: 	$config{'Qon'}=$config[10];
1.157     albertel 4853: 	$config{'PaperID'}=$config[11];
                   4854: 	$config{'PaperIDlength'}=$config[12];
                   4855: 	$config{'FirstName'}=$config[13];
                   4856: 	$config{'FirstNamelength'}=$config[14];
                   4857: 	$config{'LastName'}=$config[15];
                   4858: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4859: 	last;
                   4860:     }
                   4861:     return %config;
                   4862: }
                   4863: 
1.423     albertel 4864: =pod 
                   4865: 
                   4866: =item username_to_idmap
                   4867: 
                   4868:     creates a hash keyed by student id with values of the corresponding
                   4869:     student username:domain.
                   4870: 
                   4871:   Arguments:
                   4872: 
                   4873:     $classlist - reference to the class list hash. This is a hash
                   4874:                  keyed by student name:domain  whose elements are references
1.424     albertel 4875:                  to arrays containing various chunks of information
1.423     albertel 4876:                  about the student. (See loncoursedata for more info).
                   4877: 
                   4878:   Returns
                   4879:     %idmap - the constructed hash
                   4880: 
                   4881: =cut
                   4882: 
1.82      albertel 4883: sub username_to_idmap {
                   4884:     my ($classlist)= @_;
                   4885:     my %idmap;
                   4886:     foreach my $student (keys(%$classlist)) {
                   4887: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4888: 	    $student;
                   4889:     }
                   4890:     return %idmap;
                   4891: }
1.423     albertel 4892: 
                   4893: =pod
                   4894: 
1.424     albertel 4895: =item scantron_fixup_scanline
1.423     albertel 4896: 
                   4897:    Process a requested correction to a scanline.
                   4898: 
                   4899:   Arguments:
                   4900:     $scantron_config   - hash from &get_scantron_config()
                   4901:     $scan_data         - hash of correction information 
                   4902:                           (see &scantron_getfile())
                   4903:     $line              - existing scanline
                   4904:     $whichline         - line number of the passed in scanline
                   4905:     $field             - type of change to process 
                   4906:                          (either 
                   4907:                           'ID'     -> correct the student ID number
                   4908:                           'CODE'   -> correct the CODE
                   4909:                           'answer' -> fixup the submitted answers)
                   4910:     
                   4911:    $args               - hash of additional info,
                   4912:                           - 'ID' 
                   4913:                                'newid' -> studentID to use in replacement
1.424     albertel 4914:                                           of existing one
1.423     albertel 4915:                           - 'CODE' 
                   4916:                                'CODE_ignore_dup' - set to true if duplicates
                   4917:                                                    should be ignored.
                   4918: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 4919:                                         if the existing unfound code should
1.423     albertel 4920:                                         be used as is
                   4921:                           - 'answer'
                   4922:                                'response' - new answer or 'none' if blank
                   4923:                                'question' - the bubble line to change
                   4924: 
                   4925:   Returns:
                   4926:     $line - the modified scanline
                   4927: 
                   4928:   Side effects: 
                   4929:     $scan_data - may be updated
                   4930: 
                   4931: =cut
                   4932: 
1.82      albertel 4933: 
1.157     albertel 4934: sub scantron_fixup_scanline {
                   4935:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.423     albertel 4936: 
1.157     albertel 4937:     if ($field eq 'ID') {
                   4938: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 4939: 	    return ($line,1,'New value too large');
1.157     albertel 4940: 	}
                   4941: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   4942: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   4943: 				     $args->{'newid'});
                   4944: 	}
                   4945: 	substr($line,$$scantron_config{'IDstart'}-1,
                   4946: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   4947: 	if ($args->{'newid'}=~/^\s*$/) {
                   4948: 	    &scan_data($scan_data,"$whichline.user",
                   4949: 		       $args->{'username'}.':'.$args->{'domain'});
                   4950: 	}
1.186     albertel 4951:     } elsif ($field eq 'CODE') {
1.192     albertel 4952: 	if ($args->{'CODE_ignore_dup'}) {
                   4953: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   4954: 	}
                   4955: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   4956: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 4957: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   4958: 		return ($line,1,'New CODE value too large');
                   4959: 	    }
                   4960: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   4961: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   4962: 	    }
                   4963: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   4964: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 4965: 	}
1.157     albertel 4966:     } elsif ($field eq 'answer') {
                   4967: 	my $length=$scantron_config->{'Qlength'};
                   4968: 	my $off=$scantron_config->{'Qoff'};
                   4969: 	my $on=$scantron_config->{'Qon'};
                   4970: 	my $answer=${off}x$length;
                   4971: 	if ($args->{'response'} eq 'none') {
                   4972: 	    &scan_data($scan_data,
                   4973: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   4974: 	} else {
1.274     albertel 4975: 	    if ($on eq 'letter') {
                   4976: 		my @alphabet=('A'..'Z');
                   4977: 		$answer=$alphabet[$args->{'response'}];
                   4978: 	    } elsif ($on eq 'number') {
                   4979: 		$answer=$args->{'response'}+1;
1.389     albertel 4980: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 4981: 	    } else {
                   4982: 		substr($answer,$args->{'response'},1)=$on;
                   4983: 	    }
1.157     albertel 4984: 	    &scan_data($scan_data,
                   4985: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   4986: 	}
                   4987: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   4988: 	substr($line,$where-1,$length)=$answer;
                   4989:     }
                   4990:     return $line;
                   4991: }
1.423     albertel 4992: 
                   4993: =pod
                   4994: 
                   4995: =item scan_data
                   4996: 
                   4997:     Edit or look up  an item in the scan_data hash.
                   4998: 
                   4999:   Arguments:
                   5000:     $scan_data  - The hash (see scantron_getfile)
                   5001:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5002:                   scantronfilename_key).
1.423     albertel 5003:     $data        - New value of the hash entry.
                   5004:     $delete      - If true, the entry is removed from the hash.
                   5005: 
                   5006:   Returns:
                   5007:     The new value of the hash table field (undefined if deleted).
                   5008: 
                   5009: =cut
                   5010: 
                   5011: 
1.157     albertel 5012: sub scan_data {
                   5013:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5014:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5015:     if (defined($value)) {
                   5016: 	$scan_data->{$filename.'_'.$key} = $value;
                   5017:     }
                   5018:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5019:     return $scan_data->{$filename.'_'.$key};
                   5020: }
1.423     albertel 5021: 
                   5022: =pod 
                   5023: 
                   5024: =item scantron_parse_scanline
                   5025: 
                   5026:   Decodes a scanline from the selected scantron file
                   5027: 
                   5028:  Arguments:
                   5029:     line             - The text of the scantron file line to process
                   5030:     whichline        - Line number
                   5031:     scantron_config  - Hash describing the format of the scantron lines.
                   5032:     scan_data        - Hash of extra information about the scanline
                   5033:                        (see scantron_getfile for more information)
                   5034:     just_header      - True if should not process question answers but only
                   5035:                        the stuff to the left of the answers.
                   5036:  Returns:
                   5037:    Hash containing the result of parsing the scanline
                   5038: 
                   5039:    Keys are all proceeded by the string 'scantron.'
                   5040: 
                   5041:        CODE    - the CODE in use for this scanline
                   5042:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5043:                  by the operator
                   5044:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5045:                             CODEs were selected, but the usage has been
                   5046:                             forced by the operator
                   5047:        ID  - student ID
                   5048:        PaperID - if used, the ID number printed on the sheet when the 
                   5049:                  paper was scanned
                   5050:        FirstName - first name from the sheet
                   5051:        LastName  - last name from the sheet
                   5052: 
                   5053:      if just_header was not true these key may also exist
                   5054: 
                   5055:        missingerror - a list of bubbled line numbers that had a blank bubble
                   5056:                       that is considered an error (if the operator had already
                   5057:                       okayed a blank bubble line as really being blank then
                   5058:                       that bubble line number won't appear here.
                   5059:        doubleerror  - a list of bubbled line numbers that had more than one
                   5060:                       bubble filled in and has not been corrected by the
                   5061:                       operator
                   5062:        maxquest     - the number of the last bubble line that was parsed
                   5063: 
                   5064:        (<number> starts at 1)
                   5065:        <number>.answer - zero or more letters representing the selected
                   5066:                          letters from the scanline for the bubble line 
                   5067:                          <number>.
                   5068:                          if blank there was either no bubble or there where
                   5069:                          multiple bubbles, (consult the keys missingerror and
                   5070:                          doubleerror if this is an error condition)
                   5071: 
                   5072: =cut
                   5073: 
1.82      albertel 5074: sub scantron_parse_scanline {
1.423     albertel 5075:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.82      albertel 5076:     my %record;
1.422     foxr     5077:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5078:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5079:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5080: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5081: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5082: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5083: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5084: 	    $record{'scantron.CODE'}=substr($data,
                   5085: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5086: 					    $$scantron_config{'CODElength'});
1.191     albertel 5087: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5088: 		$record{'scantron.useCODE'}=1;
                   5089: 	    }
1.192     albertel 5090: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5091: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5092: 	    }
1.82      albertel 5093: 	} else {
                   5094: 	    #FIXME interpret first N questions
                   5095: 	}
                   5096:     }
1.83      albertel 5097:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5098: 				  $$scantron_config{'IDlength'});
1.157     albertel 5099:     $record{'scantron.PaperID'}=
                   5100: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5101: 	       $$scantron_config{'PaperIDlength'});
                   5102:     $record{'scantron.FirstName'}=
                   5103: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5104: 	       $$scantron_config{'FirstNamelength'});
                   5105:     $record{'scantron.LastName'}=
                   5106: 	substr($data,$$scantron_config{'LastName'}-1,
                   5107: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5108:     if ($just_header) { return \%record; }
1.194     albertel 5109: 
1.82      albertel 5110:     my @alphabet=('A'..'Z');
                   5111:     my $questnum=0;
                   5112:     while ($questions) {
                   5113: 	$questnum++;
                   5114: 	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
                   5115: 	substr($questions,0,$$scantron_config{'Qlength'})='';
1.83      albertel 5116: 	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
1.239     albertel 5117: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.371     albertel 5118: 	    if ($currentquest eq '?'
                   5119: 		|| $currentquest eq '*') {
1.274     albertel 5120: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5121: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 5122: 	    } elsif (!defined($currentquest)
1.274     albertel 5123: 		     || $currentquest eq $$scantron_config{'Qoff'}
                   5124: 		     || $currentquest !~ /^[A-Z]$/) {
1.239     albertel 5125: 		$record{"scantron.$questnum.answer"}='';
                   5126: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5127: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5128: 		}
                   5129: 	    } else {
                   5130: 		$record{"scantron.$questnum.answer"}=$currentquest;
                   5131: 	    }
                   5132: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.371     albertel 5133: 	    if ($currentquest eq '?'
                   5134: 		|| $currentquest eq '*') {
1.274     albertel 5135: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5136: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 5137: 	    } elsif (!defined($currentquest)
                   5138: 		     || $currentquest eq $$scantron_config{'Qoff'} 
                   5139: 		     || $currentquest !~ /^\d$/) {
1.239     albertel 5140: 		$record{"scantron.$questnum.answer"}='';
                   5141: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5142: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5143: 		}
                   5144: 	    } else {
1.371     albertel 5145: 		# wrap zero back to J
                   5146: 		if ($currentquest eq '0') {
                   5147: 		    $record{"scantron.$questnum.answer"}=
                   5148: 			$alphabet[9];
                   5149: 		} else {
                   5150: 		    $record{"scantron.$questnum.answer"}=
                   5151: 			$alphabet[$currentquest-1];
                   5152: 		}
1.239     albertel 5153: 	    }
1.82      albertel 5154: 	} else {
1.239     albertel 5155: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
                   5156: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}) {
                   5157: 		$record{"scantron.$questnum.answer"}='';
                   5158: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5159: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5160: 		}
                   5161: 	    } else {
                   5162: 		$record{"scantron.$questnum.answer"}=
                   5163: 		    $alphabet[length($array[0])];
                   5164: 	    }
                   5165: 	    if (scalar(@array) gt 2) {
                   5166: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5167: 		my @ans=@array;
                   5168: 		my $i=length($ans[0]);shift(@ans);
                   5169: 		while ($#ans) {
                   5170: 		    $i+=length($ans[0])+1;
                   5171: 		    $record{"scantron.$questnum.answer"}.=$alphabet[$i];
                   5172: 		    shift(@ans);
                   5173: 		}
                   5174: 	    }
1.82      albertel 5175: 	}
                   5176:     }
1.83      albertel 5177:     $record{'scantron.maxquest'}=$questnum;
                   5178:     return \%record;
1.82      albertel 5179: }
                   5180: 
1.423     albertel 5181: =pod
                   5182: 
                   5183: =item scantron_add_delay
                   5184: 
                   5185:    Adds an error message that occurred during the grading phase to a
                   5186:    queue of messages to be shown after grading pass is complete
                   5187: 
                   5188:  Arguments:
1.424     albertel 5189:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5190:    $scanline    - the scanline that caused the error
                   5191:    $errormesage - the error message
                   5192:    $errorcode   - a numeric code for the error
                   5193: 
                   5194:  Side Effects:
1.424     albertel 5195:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5196: 
                   5197: =cut
                   5198: 
1.82      albertel 5199: sub scantron_add_delay {
1.140     albertel 5200:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5201:     push(@$delayqueue,
                   5202: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5203: 	  'ecode' => $errorcode }
                   5204: 	 );
1.82      albertel 5205: }
                   5206: 
1.423     albertel 5207: =pod
                   5208: 
                   5209: =item scantron_find_student
                   5210: 
1.424     albertel 5211:    Finds the username for the current scanline
                   5212: 
                   5213:   Arguments:
                   5214:    $scantron_record - hash result from scantron_parse_scanline
                   5215:    $scan_data       - hash of correction information 
                   5216:                       (see &scantron_getfile() form more information)
                   5217:    $idmap           - hash from &username_to_idmap()
                   5218:    $line            - number of current scanline
                   5219:  
                   5220:   Returns:
                   5221:    Either 'username:domain' or undef if unknown
                   5222: 
1.423     albertel 5223: =cut
                   5224: 
1.82      albertel 5225: sub scantron_find_student {
1.157     albertel 5226:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5227:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5228:     if ($scanID =~ /^\s*$/) {
                   5229:  	return &scan_data($scan_data,"$line.user");
                   5230:     }
1.83      albertel 5231:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5232:  	if (lc($id) eq lc($scanID)) {
                   5233:  	    return $$idmap{$id};
                   5234:  	}
1.83      albertel 5235:     }
                   5236:     return undef;
                   5237: }
                   5238: 
1.423     albertel 5239: =pod
                   5240: 
                   5241: =item scantron_filter
                   5242: 
1.424     albertel 5243:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5244:    hidden resources was selected
                   5245: 
1.423     albertel 5246: =cut
                   5247: 
1.83      albertel 5248: sub scantron_filter {
                   5249:     my ($curres)=@_;
1.331     albertel 5250: 
                   5251:     if (ref($curres) && $curres->is_problem()) {
                   5252: 	# if the user has asked to not have either hidden
                   5253: 	# or 'randomout' controlled resources to be graded
                   5254: 	# don't include them
                   5255: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5256: 	    && $curres->randomout) {
                   5257: 	    return 0;
                   5258: 	}
1.83      albertel 5259: 	return 1;
                   5260:     }
                   5261:     return 0;
1.82      albertel 5262: }
                   5263: 
1.423     albertel 5264: =pod
                   5265: 
                   5266: =item scantron_process_corrections
                   5267: 
1.424     albertel 5268:    Gets correction information out of submitted form data and corrects
                   5269:    the scanline
                   5270: 
1.423     albertel 5271: =cut
                   5272: 
1.157     albertel 5273: sub scantron_process_corrections {
                   5274:     my ($r) = @_;
1.257     albertel 5275:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5276:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5277:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5278:     my $which=$env{'form.scantron_line'};
1.200     albertel 5279:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5280:     my ($skip,$err,$errmsg);
1.257     albertel 5281:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5282: 	$skip=1;
1.257     albertel 5283:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5284: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5285: 	    $env{'form.scantron_domain'};
1.157     albertel 5286: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5287: 	($line,$err,$errmsg)=
                   5288: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5289: 				     'ID',{'newid'=>$newid,
1.257     albertel 5290: 				    'username'=>$env{'form.scantron_username'},
                   5291: 				    'domain'=>$env{'form.scantron_domain'}});
                   5292:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5293: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5294: 	my $newCODE;
1.192     albertel 5295: 	my %args;
1.190     albertel 5296: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5297: 	    $newCODE='use_unfound';
1.190     albertel 5298: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5299: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5300: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5301: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5302: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5303: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5304: 	}
1.257     albertel 5305: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5306: 	    $args{'CODE_ignore_dup'}=1;
                   5307: 	}
                   5308: 	$args{'CODE'}=$newCODE;
1.186     albertel 5309: 	($line,$err,$errmsg)=
                   5310: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5311: 				     'CODE',\%args);
1.257     albertel 5312:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5313: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5314: 	    ($line,$err,$errmsg)=
                   5315: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5316: 					 $which,'answer',
                   5317: 					 { 'question'=>$question,
1.257     albertel 5318: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5319: 	    if ($err) { last; }
                   5320: 	}
                   5321:     }
                   5322:     if ($err) {
1.398     albertel 5323: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5324:     } else {
1.200     albertel 5325: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5326: 	&scantron_putfile($scanlines,$scan_data);
                   5327:     }
                   5328: }
                   5329: 
1.423     albertel 5330: =pod
                   5331: 
                   5332: =item reset_skipping_status
                   5333: 
1.424     albertel 5334:    Forgets the current set of remember skipped scanlines (and thus
                   5335:    reverts back to considering all lines in the
                   5336:    scantron_skipped_<filename> file)
                   5337: 
1.423     albertel 5338: =cut
                   5339: 
1.200     albertel 5340: sub reset_skipping_status {
                   5341:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5342:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5343:     &scantron_putfile(undef,$scan_data);
                   5344: }
                   5345: 
1.423     albertel 5346: =pod
                   5347: 
                   5348: =item start_skipping
                   5349: 
1.424     albertel 5350:    Marks a scanline to be skipped. 
                   5351: 
1.423     albertel 5352: =cut
                   5353: 
1.376     albertel 5354: sub start_skipping {
1.200     albertel 5355:     my ($scan_data,$i)=@_;
                   5356:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5357:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5358: 	$remembered{$i}=2;
                   5359:     } else {
                   5360: 	$remembered{$i}=1;
                   5361:     }
1.200     albertel 5362:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5363: }
                   5364: 
1.423     albertel 5365: =pod
                   5366: 
                   5367: =item should_be_skipped
                   5368: 
1.424     albertel 5369:    Checks whether a scanline should be skipped.
                   5370: 
1.423     albertel 5371: =cut
                   5372: 
1.200     albertel 5373: sub should_be_skipped {
1.376     albertel 5374:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5375:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5376: 	# not redoing old skips
1.376     albertel 5377: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5378: 	return 0;
                   5379:     }
                   5380:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5381: 
                   5382:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5383: 	return 0;
                   5384:     }
1.200     albertel 5385:     return 1;
                   5386: }
                   5387: 
1.423     albertel 5388: =pod
                   5389: 
                   5390: =item remember_current_skipped
                   5391: 
1.424     albertel 5392:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5393:    file and remembers them into scan_data for later use.
                   5394: 
1.423     albertel 5395: =cut
                   5396: 
1.200     albertel 5397: sub remember_current_skipped {
                   5398:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5399:     my %to_remember;
                   5400:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5401: 	if ($scanlines->{'skipped'}[$i]) {
                   5402: 	    $to_remember{$i}=1;
                   5403: 	}
                   5404:     }
1.376     albertel 5405: 
1.200     albertel 5406:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5407:     &scantron_putfile(undef,$scan_data);
                   5408: }
                   5409: 
1.423     albertel 5410: =pod
                   5411: 
                   5412: =item check_for_error
                   5413: 
1.424     albertel 5414:     Checks if there was an error when attempting to remove a specific
                   5415:     scantron_.. bubble sheet data file. Prints out an error if
                   5416:     something went wrong.
                   5417: 
1.423     albertel 5418: =cut
                   5419: 
1.200     albertel 5420: sub check_for_error {
                   5421:     my ($r,$result)=@_;
                   5422:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5423: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5424:     }
                   5425: }
1.157     albertel 5426: 
1.423     albertel 5427: =pod
                   5428: 
                   5429: =item scantron_warning_screen
                   5430: 
1.424     albertel 5431:    Interstitial screen to make sure the operator has selected the
                   5432:    correct options before we start the validation phase.
                   5433: 
1.423     albertel 5434: =cut
                   5435: 
1.203     albertel 5436: sub scantron_warning_screen {
                   5437:     my ($button_text)=@_;
1.257     albertel 5438:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5439:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5440:     my $CODElist;
1.284     albertel 5441:     if ($scantron_config{'CODElocation'} &&
                   5442: 	$scantron_config{'CODEstart'} &&
                   5443: 	$scantron_config{'CODElength'}) {
                   5444: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5445: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5446: 	$CODElist=
                   5447: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5448: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5449:     }
1.203     albertel 5450:     return (<<STUFF);
                   5451: <p>
1.398     albertel 5452: <span class="LC_warning">Please double check the information
                   5453:                  below before clicking on '$button_text'</span>
1.203     albertel 5454: </p>
                   5455: <table>
1.284     albertel 5456: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5457: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5458: $CODElist
1.203     albertel 5459: </table>
                   5460: <br />
                   5461: <p> If this information is correct, please click on '$button_text'.</p>
                   5462: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5463: 
                   5464: <br />
                   5465: STUFF
                   5466: }
                   5467: 
1.423     albertel 5468: =pod
                   5469: 
                   5470: =item scantron_do_warning
                   5471: 
1.424     albertel 5472:    Check if the operator has picked something for all required
                   5473:    fields. Error out if something is missing.
                   5474: 
1.423     albertel 5475: =cut
                   5476: 
1.203     albertel 5477: sub scantron_do_warning {
                   5478:     my ($r)=@_;
1.324     albertel 5479:     my ($symb)=&get_symb($r);
1.203     albertel 5480:     if (!$symb) {return '';}
1.324     albertel 5481:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5482:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5483:     if ( $env{'form.selectpage'} eq '' ||
                   5484: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5485: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5486: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5487: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5488: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5489: 	} 
1.257     albertel 5490: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5491: 	    $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 5492: 	} 
1.257     albertel 5493: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5494: 	    $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 5495: 	} 
                   5496:     } else {
1.265     www      5497: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5498: 	$r->print(<<STUFF);
1.203     albertel 5499: $warning
1.265     www      5500: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5501: <input type="hidden" name="command" value="scantron_validate" />
                   5502: STUFF
1.237     albertel 5503:     }
1.352     albertel 5504:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5505:     return '';
                   5506: }
                   5507: 
1.423     albertel 5508: =pod
                   5509: 
                   5510: =item scantron_form_start
                   5511: 
1.424     albertel 5512:     html hidden input for remembering all selected grading options
                   5513: 
1.423     albertel 5514: =cut
                   5515: 
1.203     albertel 5516: sub scantron_form_start {
                   5517:     my ($max_bubble)=@_;
                   5518:     my $result= <<SCANTRONFORM;
                   5519: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5520:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5521:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5522:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5523:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5524:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5525:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5526:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5527:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5528:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5529: SCANTRONFORM
                   5530:     return $result;
                   5531: }
                   5532: 
1.423     albertel 5533: =pod
                   5534: 
                   5535: =item scantron_validate_file
                   5536: 
1.424     albertel 5537:     Dispatch routine for doing validation of a bubble sheet data file.
                   5538: 
                   5539:     Also processes any necessary information resets that need to
                   5540:     occur before validation begins (ignore previous corrections,
                   5541:     restarting the skipped records processing)
                   5542: 
1.423     albertel 5543: =cut
                   5544: 
1.157     albertel 5545: sub scantron_validate_file {
                   5546:     my ($r) = @_;
1.324     albertel 5547:     my ($symb)=&get_symb($r);
1.157     albertel 5548:     if (!$symb) {return '';}
1.324     albertel 5549:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5550:     
                   5551:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5552:     # them when doing the corrections reset
1.257     albertel 5553:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5554: 	&reset_skipping_status();
                   5555:     }
1.257     albertel 5556:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5557: 	&remember_current_skipped();
1.257     albertel 5558: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5559:     }
                   5560: 
1.257     albertel 5561:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5562: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5563: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5564: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5565: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5566:     }
1.200     albertel 5567: 
1.257     albertel 5568:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5569: 	&scantron_process_corrections($r);
                   5570:     }
1.424     albertel 5571:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5572:     #get the student pick code ready
                   5573:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5574:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5575:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5576:     $r->print($result);
                   5577:     
1.334     albertel 5578:     my @validate_phases=( 'sequence',
                   5579: 			  'ID',
1.157     albertel 5580: 			  'CODE',
                   5581: 			  'doublebubble',
                   5582: 			  'missingbubbles');
1.257     albertel 5583:     if (!$env{'form.validatepass'}) {
                   5584: 	$env{'form.validatepass'} = 0;
1.157     albertel 5585:     }
1.257     albertel 5586:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5587: 
                   5588:     my $stop=0;
                   5589:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5590: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5591: 	$r->rflush();
                   5592: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5593: 	{
                   5594: 	    no strict 'refs';
                   5595: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5596: 	}
                   5597:     }
                   5598:     if (!$stop) {
1.203     albertel 5599: 	my $warning=&scantron_warning_screen('Start Grading');
                   5600: 	$r->print(<<STUFF);
                   5601: Validation process complete.<br />
                   5602: $warning
                   5603: <input type="submit" name="submit" value="Start Grading" />
                   5604: <input type="hidden" name="command" value="scantron_process" />
                   5605: STUFF
                   5606: 
1.157     albertel 5607:     } else {
                   5608: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5609: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5610:     }
                   5611:     if ($stop) {
1.334     albertel 5612: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5613: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5614: 	    $r->print(' this error <br />');
                   5615: 
                   5616: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5617: 	} else {
                   5618: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5619: 	    $r->print(' using corrected info <br />');
                   5620: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5621: 	    $r->print(" this scanline saving it for later.");
                   5622: 	}
1.157     albertel 5623:     }
1.352     albertel 5624:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5625:     return '';
                   5626: }
                   5627: 
1.423     albertel 5628: 
                   5629: =pod
                   5630: 
                   5631: =item scantron_remove_file
                   5632: 
1.424     albertel 5633:    Removes the requested bubble sheet data file, makes sure that
                   5634:    scantron_original_<filename> is never removed
                   5635: 
                   5636: 
1.423     albertel 5637: =cut
                   5638: 
1.200     albertel 5639: sub scantron_remove_file {
1.192     albertel 5640:     my ($which)=@_;
1.257     albertel 5641:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5642:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5643:     my $file='scantron_';
1.200     albertel 5644:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5645: 	$file.=$which.'_';
1.192     albertel 5646:     } else {
                   5647: 	return 'refused';
                   5648:     }
1.257     albertel 5649:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5650:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5651: }
                   5652: 
1.423     albertel 5653: 
                   5654: =pod
                   5655: 
                   5656: =item scantron_remove_scan_data
                   5657: 
1.424     albertel 5658:    Removes all scan_data correction for the requested bubble sheet
                   5659:    data file.  (In the case that both the are doing skipped records we need
                   5660:    to remember the old skipped lines for the time being so that element
                   5661:    persists for a while.)
                   5662: 
1.423     albertel 5663: =cut
                   5664: 
1.200     albertel 5665: sub scantron_remove_scan_data {
1.257     albertel 5666:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5667:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5668:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5669:     my @todelete;
1.257     albertel 5670:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5671:     foreach my $key (@keys) {
                   5672: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5673: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5674: 		$key=~/remember_skipping/) {
                   5675: 		next;
                   5676: 	    }
1.192     albertel 5677: 	    push(@todelete,$key);
                   5678: 	}
                   5679:     }
1.200     albertel 5680:     my $result;
1.192     albertel 5681:     if (@todelete) {
1.200     albertel 5682: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5683:     }
                   5684:     return $result;
                   5685: }
                   5686: 
1.423     albertel 5687: 
                   5688: =pod
                   5689: 
                   5690: =item scantron_getfile
                   5691: 
1.424     albertel 5692:     Fetches the requested bubble sheet data file (all 3 versions), and
                   5693:     the scan_data hash
                   5694:   
                   5695:   Arguments:
                   5696:     None
                   5697: 
                   5698:   Returns:
                   5699:     2 hash references
                   5700: 
                   5701:      - first one has 
                   5702:          orig      -
                   5703:          corrected -
                   5704:          skipped   -  each of which points to an array ref of the specified
                   5705:                       file broken up into individual lines
                   5706:          count     - number of scanlines
                   5707:  
                   5708:      - second is the scan_data hash possible keys are
1.425     albertel 5709:        ($number refers to scanline numbered $number and thus the key affects
                   5710:         only that scanline
                   5711:         $bubline refers to the specific bubble line element and the aspects
                   5712:         refers to that specific bubble line element)
                   5713: 
                   5714:        $number.user - username:domain to use
                   5715:        $number.CODE_ignore_dup 
                   5716:                     - ignore the duplicate CODE error 
                   5717:        $number.useCODE
                   5718:                     - use the CODE in the scanline as is
                   5719:        $number.no_bubble.$bubline
                   5720:                     - it is valid that there is no bubbled in bubble
                   5721:                       at $number $bubline
                   5722:        remember_skipping
                   5723:                     - a frozen hash containing keys of $number and values
                   5724:                       of either 
                   5725:                         1 - we are on a 'do skipped records pass' and plan
                   5726:                             on processing this line
                   5727:                         2 - we are on a 'do skipped records pass' and this
                   5728:                             scanline has been marked to skip yet again
1.424     albertel 5729: 
1.423     albertel 5730: =cut
                   5731: 
1.157     albertel 5732: sub scantron_getfile {
1.200     albertel 5733:     #FIXME really would prefer a scantron directory
1.257     albertel 5734:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5735:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5736:     my $lines;
                   5737:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5738: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5739:     my %scanlines;
                   5740:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5741:     my $temp=$scanlines{'orig'};
                   5742:     $scanlines{'count'}=$#$temp;
                   5743: 
                   5744:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5745: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5746:     if ($lines eq '-1') {
                   5747: 	$scanlines{'corrected'}=[];
                   5748:     } else {
                   5749: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5750:     }
                   5751:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5752: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5753:     if ($lines eq '-1') {
                   5754: 	$scanlines{'skipped'}=[];
                   5755:     } else {
                   5756: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5757:     }
1.175     albertel 5758:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5759:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5760:     my %scan_data = @tmp;
                   5761:     return (\%scanlines,\%scan_data);
                   5762: }
                   5763: 
1.423     albertel 5764: =pod
                   5765: 
                   5766: =item lonnet_putfile
                   5767: 
1.424     albertel 5768:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   5769: 
                   5770:  Arguments:
                   5771:    $contents - data to store
                   5772:    $filename - filename to store $contents into
                   5773: 
                   5774:  Returns:
                   5775:    result value from &Apache::lonnet::finishuserfileupload
                   5776: 
1.423     albertel 5777: =cut
                   5778: 
1.157     albertel 5779: sub lonnet_putfile {
                   5780:     my ($contents,$filename)=@_;
1.257     albertel 5781:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5782:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5783:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 5784:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 5785: 
                   5786: }
                   5787: 
1.423     albertel 5788: =pod
                   5789: 
                   5790: =item scantron_putfile
                   5791: 
1.424     albertel 5792:     Stores the current version of the bubble sheet data files, and the
                   5793:     scan_data hash. (Does not modify the original version only the
                   5794:     corrected and skipped versions.
                   5795: 
                   5796:  Arguments:
                   5797:     $scanlines - hash ref that looks like the first return value from
                   5798:                  &scantron_getfile()
                   5799:     $scan_data - hash ref that looks like the second return value from
                   5800:                  &scantron_getfile()
                   5801: 
1.423     albertel 5802: =cut
                   5803: 
1.157     albertel 5804: sub scantron_putfile {
                   5805:     my ($scanlines,$scan_data) = @_;
1.200     albertel 5806:     #FIXME really would prefer a scantron directory
1.257     albertel 5807:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5808:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 5809:     if ($scanlines) {
                   5810: 	my $prefix='scantron_';
1.157     albertel 5811: # no need to update orig, shouldn't change
                   5812: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 5813: #		    $env{'form.scantron_selectfile'});
1.200     albertel 5814: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   5815: 			$prefix.'corrected_'.
1.257     albertel 5816: 			$env{'form.scantron_selectfile'});
1.200     albertel 5817: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   5818: 			$prefix.'skipped_'.
1.257     albertel 5819: 			$env{'form.scantron_selectfile'});
1.200     albertel 5820:     }
1.175     albertel 5821:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 5822: }
                   5823: 
1.423     albertel 5824: =pod
                   5825: 
                   5826: =item scantron_get_line
                   5827: 
1.424     albertel 5828:    Returns the correct version of the scanline
                   5829: 
                   5830:  Arguments:
                   5831:     $scanlines - hash ref that looks like the first return value from
                   5832:                  &scantron_getfile()
                   5833:     $scan_data - hash ref that looks like the second return value from
                   5834:                  &scantron_getfile()
                   5835:     $i         - number of the requested line (starts at 0)
                   5836: 
                   5837:  Returns:
                   5838:    A scanline, (either the original or the corrected one if it
                   5839:    exists), or undef if the requested scanline should be
                   5840:    skipped. (Either because it's an skipped scanline, or it's an
                   5841:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   5842:    pass.
                   5843: 
1.423     albertel 5844: =cut
                   5845: 
1.157     albertel 5846: sub scantron_get_line {
1.200     albertel 5847:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 5848:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   5849:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 5850:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   5851:     return $scanlines->{'orig'}[$i]; 
                   5852: }
                   5853: 
1.423     albertel 5854: =pod
                   5855: 
                   5856: =item scantron_todo_count
                   5857: 
1.424     albertel 5858:     Counts the number of scanlines that need processing.
                   5859: 
                   5860:  Arguments:
                   5861:     $scanlines - hash ref that looks like the first return value from
                   5862:                  &scantron_getfile()
                   5863:     $scan_data - hash ref that looks like the second return value from
                   5864:                  &scantron_getfile()
                   5865: 
                   5866:  Returns:
                   5867:     $count - number of scanlines to process
                   5868: 
1.423     albertel 5869: =cut
                   5870: 
1.200     albertel 5871: sub get_todo_count {
                   5872:     my ($scanlines,$scan_data)=@_;
                   5873:     my $count=0;
                   5874:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5875: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   5876: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5877: 	$count++;
                   5878:     }
                   5879:     return $count;
                   5880: }
                   5881: 
1.423     albertel 5882: =pod
                   5883: 
                   5884: =item scantron_put_line
                   5885: 
1.424     albertel 5886:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   5887:     data file.
                   5888: 
                   5889:  Arguments:
                   5890:     $scanlines - hash ref that looks like the first return value from
                   5891:                  &scantron_getfile()
                   5892:     $scan_data - hash ref that looks like the second return value from
                   5893:                  &scantron_getfile()
                   5894:     $i         - line number to update
                   5895:     $newline   - contents of the updated scanline
                   5896:     $skip      - if true make the line for skipping and update the
                   5897:                  'skipped' file
                   5898: 
1.423     albertel 5899: =cut
                   5900: 
1.157     albertel 5901: sub scantron_put_line {
1.200     albertel 5902:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 5903:     if ($skip) {
                   5904: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 5905: 	&start_skipping($scan_data,$i);
1.157     albertel 5906: 	return;
                   5907:     }
                   5908:     $scanlines->{'corrected'}[$i]=$newline;
                   5909: }
                   5910: 
1.423     albertel 5911: =pod
                   5912: 
                   5913: =item scantron_clear_skip
                   5914: 
1.424     albertel 5915:    Remove a line from the 'skipped' file
                   5916: 
                   5917:  Arguments:
                   5918:     $scanlines - hash ref that looks like the first return value from
                   5919:                  &scantron_getfile()
                   5920:     $scan_data - hash ref that looks like the second return value from
                   5921:                  &scantron_getfile()
                   5922:     $i         - line number to update
                   5923: 
1.423     albertel 5924: =cut
                   5925: 
1.376     albertel 5926: sub scantron_clear_skip {
                   5927:     my ($scanlines,$scan_data,$i)=@_;
                   5928:     if (exists($scanlines->{'skipped'}[$i])) {
                   5929: 	undef($scanlines->{'skipped'}[$i]);
                   5930: 	return 1;
                   5931:     }
                   5932:     return 0;
                   5933: }
                   5934: 
1.423     albertel 5935: =pod
                   5936: 
                   5937: =item scantron_filter_not_exam
                   5938: 
1.424     albertel 5939:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   5940:    filter out resources that are not marked as 'exam' mode
                   5941: 
1.423     albertel 5942: =cut
                   5943: 
1.334     albertel 5944: sub scantron_filter_not_exam {
                   5945:     my ($curres)=@_;
                   5946:     
                   5947:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   5948: 	# if the user has asked to not have either hidden
                   5949: 	# or 'randomout' controlled resources to be graded
                   5950: 	# don't include them
                   5951: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5952: 	    && $curres->randomout) {
                   5953: 	    return 0;
                   5954: 	}
                   5955: 	return 1;
                   5956:     }
                   5957:     return 0;
                   5958: }
                   5959: 
1.423     albertel 5960: =pod
                   5961: 
                   5962: =item scantron_validate_sequence
                   5963: 
1.424     albertel 5964:     Validates the selected sequence, checking for resource that are
                   5965:     not set to exam mode.
                   5966: 
1.423     albertel 5967: =cut
                   5968: 
1.334     albertel 5969: sub scantron_validate_sequence {
                   5970:     my ($r,$currentphase) = @_;
                   5971: 
                   5972:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5973:     my (undef,undef,$sequence)=
                   5974: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   5975: 
                   5976:     my $map=$navmap->getResourceByUrl($sequence);
                   5977: 
                   5978:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   5979:                                     value="ignore" />');
                   5980:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   5981: 	my @resources=
                   5982: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   5983: 	if (@resources) {
1.357     banghart 5984: 	    $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 5985: 	    return (1,$currentphase);
                   5986: 	}
                   5987:     }
                   5988: 
                   5989:     return (0,$currentphase+1);
                   5990: }
                   5991: 
1.423     albertel 5992: =pod
                   5993: 
                   5994: =item scantron_validate_ID
                   5995: 
1.424     albertel 5996:    Validates all scanlines in the selected file to not have any
                   5997:    invalid or underspecified student IDs
                   5998: 
1.423     albertel 5999: =cut
                   6000: 
1.157     albertel 6001: sub scantron_validate_ID {
                   6002:     my ($r,$currentphase) = @_;
                   6003:     
                   6004:     #get student info
                   6005:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6006:     my %idmap=&username_to_idmap($classlist);
                   6007: 
                   6008:     #get scantron line setup
1.257     albertel 6009:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6010:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6011: 
                   6012:     my %found=('ids'=>{},'usernames'=>{});
                   6013:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6014: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6015: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6016: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6017: 						 $scan_data);
                   6018: 	my $id=$$scan_record{'scantron.ID'};
                   6019: 	my $found;
                   6020: 	foreach my $checkid (keys(%idmap)) {
                   6021: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6022: 	}
                   6023: 	if ($found) {
                   6024: 	    my $username=$idmap{$found};
                   6025: 	    if ($found{'ids'}{$found}) {
                   6026: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6027: 					 $line,'duplicateID',$found);
1.194     albertel 6028: 		return(1,$currentphase);
1.157     albertel 6029: 	    } elsif ($found{'usernames'}{$username}) {
                   6030: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6031: 					 $line,'duplicateID',$username);
1.194     albertel 6032: 		return(1,$currentphase);
1.157     albertel 6033: 	    }
1.186     albertel 6034: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6035: 	    $found{'ids'}{$found}++;
                   6036: 	    $found{'usernames'}{$username}++;
                   6037: 	} else {
                   6038: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6039: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6040: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6041: 		    &scantron_get_correction($r,$i,$scan_record,
                   6042: 					     \%scantron_config,
                   6043: 					     $line,'duplicateID',$username);
1.194     albertel 6044: 		    return(1,$currentphase);
1.157     albertel 6045: 		} elsif (!defined($username)) {
                   6046: 		    &scantron_get_correction($r,$i,$scan_record,
                   6047: 					     \%scantron_config,
                   6048: 					     $line,'incorrectID');
1.194     albertel 6049: 		    return(1,$currentphase);
1.157     albertel 6050: 		}
                   6051: 		$found{'usernames'}{$username}++;
                   6052: 	    } else {
                   6053: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6054: 					 $line,'incorrectID');
1.194     albertel 6055: 		return(1,$currentphase);
1.157     albertel 6056: 	    }
                   6057: 	}
                   6058:     }
                   6059: 
                   6060:     return (0,$currentphase+1);
                   6061: }
                   6062: 
1.423     albertel 6063: =pod
                   6064: 
                   6065: =item scantron_get_correction
                   6066: 
1.424     albertel 6067:    Builds the interface screen to interact with the operator to fix a
                   6068:    specific error condition in a specific scanline
                   6069: 
                   6070:  Arguments:
                   6071:     $r           - Apache request object
                   6072:     $i           - number of the current scanline
                   6073:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6074:     $scan_config - hash ref as returned from &get_scantron_config()
                   6075:     $line        - full contents of the current scanline
                   6076:     $error       - error condition, valid values are
                   6077:                    'incorrectCODE', 'duplicateCODE',
                   6078:                    'doublebubble', 'missingbubble',
                   6079:                    'duplicateID', 'incorrectID'
                   6080:     $arg         - extra information needed
                   6081:        For errors:
                   6082:          - duplicateID   - paper number that this studentID was seen before on
                   6083:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6084:                            seen on before
                   6085:          - incorrectCODE - current incorrect CODE 
                   6086:          - doublebubble  - array ref of the bubble lines that have double
                   6087:                            bubble errors
                   6088:          - missingbubble - array ref of the bubble lines that have missing
                   6089:                            bubble errors
                   6090: 
1.423     albertel 6091: =cut
                   6092: 
1.157     albertel 6093: sub scantron_get_correction {
                   6094:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6095: 
                   6096: #FIXME in the case of a duplicated ID the previous line, probaly need
                   6097: #to show both the current line and the previous one and allow skipping
                   6098: #the previous one or the current one
                   6099: 
1.161     albertel 6100:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6101:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6102: 	$r->print(" for PaperID <tt>".
                   6103: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6104:     } else {
                   6105: 	$r->print(" in scanline $i <pre>".
                   6106: 		  $line."</pre> \n");
                   6107:     }
1.242     albertel 6108:     my $message="<p>The ID on the form is  <tt>".
                   6109: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6110: 	"The name on the paper is ".
                   6111: 	$$scan_record{'scantron.LastName'}.",".
                   6112: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6113: 
1.157     albertel 6114:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6115:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6116:     if ($error =~ /ID$/) {
1.186     albertel 6117: 	if ($error eq 'incorrectID') {
1.157     albertel 6118: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6119: 	} elsif ($error eq 'duplicateID') {
                   6120: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6121: 	}
1.242     albertel 6122: 	$r->print($message);
1.157     albertel 6123: 	$r->print("<p>How should I handle this? <br /> \n");
                   6124: 	$r->print("\n<ul><li> ");
                   6125: 	#FIXME it would be nice if this sent back the user ID and
                   6126: 	#could do partial userID matches
                   6127: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6128: 				       'scantron_username','scantron_domain'));
                   6129: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6130: 	$r->print("\n@".
1.257     albertel 6131: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6132: 
                   6133: 	$r->print('</li>');
1.186     albertel 6134:     } elsif ($error =~ /CODE$/) {
                   6135: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6136: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6137: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6138: 	    $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 6139: 	}
1.224     albertel 6140: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6141: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6142: 	$r->print($message);
1.186     albertel 6143: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6144: 	$r->print("\n<br /> ");
1.194     albertel 6145: 	my $i=0;
1.273     albertel 6146: 	if ($error eq 'incorrectCODE' 
                   6147: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6148: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6149: 	    if ($closest > 0) {
                   6150: 		foreach my $testcode (@{$closest}) {
                   6151: 		    my $checked='';
1.401     albertel 6152: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6153: 		    $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' />");
                   6154: 		    $r->print("\n<br />");
                   6155: 		    $i++;
                   6156: 		}
1.194     albertel 6157: 	    }
                   6158: 	}
1.273     albertel 6159: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6160: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6161: 	    $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>");
                   6162: 	    $r->print("\n<br />");
                   6163: 	}
1.194     albertel 6164: 
1.188     albertel 6165: 	$r->print(<<ENDSCRIPT);
                   6166: <script type="text/javascript">
                   6167: function change_radio(field) {
1.190     albertel 6168:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6169:     var i;
                   6170:     for (i=0;i<slct.length;i++) {
                   6171:         if (slct[i].value==field) { slct[i].checked=true; }
                   6172:     }
                   6173: }
                   6174: </script>
                   6175: ENDSCRIPT
1.187     albertel 6176: 	my $href="/adm/pickcode?".
1.359     www      6177: 	   "form=".&escape("scantronupload").
                   6178: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6179: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6180: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6181: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6182: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6183: 	    $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')\" />");
                   6184: 	    $r->print("\n<br />");
                   6185: 	}
1.272     albertel 6186: 	$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 6187: 	$r->print("\n<br /><br />");
1.157     albertel 6188:     } elsif ($error eq 'doublebubble') {
                   6189: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6190: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6191: 		  join(',',@{$arg}).'" />');
1.242     albertel 6192: 	$r->print($message);
1.157     albertel 6193: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6194: 	foreach my $question (@{$arg}) {
                   6195: 	    my $selected=$$scan_record{"scantron.$question.answer"};
1.422     foxr     6196: 	    &scantron_bubble_selector($r,$scan_config,$question,
                   6197: 				      split('',$selected));
1.157     albertel 6198: 	}
                   6199:     } elsif ($error eq 'missingbubble') {
                   6200: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6201: 	$r->print($message);
1.157     albertel 6202: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6203: 	$r->print("Some questions have no scanned bubbles\n");
                   6204: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6205: 		  join(',',@{$arg}).'" />');
                   6206: 	foreach my $question (@{$arg}) {
                   6207: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   6208: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   6209: 	}
                   6210:     } else {
                   6211: 	$r->print("\n<ul>");
                   6212:     }
                   6213:     $r->print("\n</li></ul>");
                   6214: 
                   6215: }
1.423     albertel 6216: 
                   6217: =pod
                   6218: 
                   6219: =item scantron_bubble_selector
                   6220:   
                   6221:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6222:    possibly showing the existing the selected bubbles if known
1.423     albertel 6223: 
                   6224:  Arguments:
                   6225:     $r           - Apache request object
                   6226:     $scan_config - hash from &get_scantron_config()
                   6227:     $quest       - number of the bubble line to make a corrector for
                   6228:     $selected    - array of letters of previously selected bubbles
                   6229:     $lines       - if present, number of bubble lines to show
                   6230: 
                   6231: =cut
                   6232: 
1.157     albertel 6233: sub scantron_bubble_selector {
1.422     foxr     6234:     my ($r,$scan_config,$quest,@selected, $lines)=@_;
1.157     albertel 6235:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6236: 
                   6237:     my $scmode=$$scan_config{'Qon'};
                   6238:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6239: 
1.422     foxr     6240: 
                   6241:     if (!defined($lines)) {
                   6242: 	$lines = 1;
                   6243:     }
                   6244:     my $total_lines = $lines*2;
1.157     albertel 6245:     my @alphabet=('A'..'Z');
1.422     foxr     6246:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6247: 
                   6248:     for (my $l = 0; $l < $lines; $l++) {
                   6249: 	if ($l != 0) {
                   6250: 	    $r->print('<tr>');
                   6251: 	}
                   6252: 
                   6253: 	# FIXME:  This loop probably has to be considerably more clever for
                   6254: 	#  multiline bubbles: User can multibubble by having bubbles in
                   6255: 	#  several lines.  User can skip lines legitimately etc. etc.
                   6256: 
                   6257: 	for (my $i=0;$i<$max;$i++) {
                   6258: 	    $r->print("\n".'<td align="center">');
                   6259: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6260: 		$r->print('X'); 
                   6261: 		shift(@selected) ;
                   6262: 	    } else { 
                   6263: 		$r->print('&nbsp;'); 
                   6264: 	    }
                   6265: 	    $r->print('</td>');
                   6266: 	    
                   6267: 	}
                   6268: 
                   6269: 	if ($l == 0) {
                   6270: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6271: 
                   6272: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6273: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6274: 	
                   6275: 	}
                   6276: 
                   6277: 	$r->print('</tr><tr>');
                   6278: 
                   6279: 	# FIXME: This may have to be a bit more clever for
                   6280: 	#        multiline questions (different values e.g..).
                   6281: 
                   6282: 	for (my $i=0;$i<$max;$i++) {
                   6283: 	    $r->print("\n".
                   6284: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6285: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6286: 	}
                   6287: 	$r->print('</tr>');
                   6288: 
                   6289: 	    
1.157     albertel 6290:     }
1.422     foxr     6291:     $r->print('</table>');
1.157     albertel 6292: }
                   6293: 
1.423     albertel 6294: =pod
                   6295: 
                   6296: =item num_matches
                   6297: 
1.424     albertel 6298:    Counts the number of characters that are the same between the two arguments.
                   6299: 
                   6300:  Arguments:
                   6301:    $orig - CODE from the scanline
                   6302:    $code - CODE to match against
                   6303: 
                   6304:  Returns:
                   6305:    $count - integer count of the number of same characters between the
                   6306:             two arguments
                   6307: 
1.423     albertel 6308: =cut
                   6309: 
1.194     albertel 6310: sub num_matches {
                   6311:     my ($orig,$code) = @_;
                   6312:     my @code=split(//,$code);
                   6313:     my @orig=split(//,$orig);
                   6314:     my $same=0;
                   6315:     for (my $i=0;$i<scalar(@code);$i++) {
                   6316: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6317:     }
                   6318:     return $same;
                   6319: }
                   6320: 
1.423     albertel 6321: =pod
                   6322: 
                   6323: =item scantron_get_closely_matching_CODEs
                   6324: 
1.424     albertel 6325:    Cycles through all CODEs and finds the set that has the greatest
                   6326:    number of same characters as the provided CODE
                   6327: 
                   6328:  Arguments:
                   6329:    $allcodes - hash ref returned by &get_codes()
                   6330:    $CODE     - CODE from the current scanline
                   6331: 
                   6332:  Returns:
                   6333:    2 element list
                   6334:     - first elements is number of how closely matching the best fit is 
                   6335:       (5 means best set has 5 matching characters)
                   6336:     - second element is an arrary ref containing the set of valid CODEs
                   6337:       that best fit the passed in CODE
                   6338: 
1.423     albertel 6339: =cut
                   6340: 
1.194     albertel 6341: sub scantron_get_closely_matching_CODEs {
                   6342:     my ($allcodes,$CODE)=@_;
                   6343:     my @CODEs;
                   6344:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6345: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6346:     }
                   6347: 
                   6348:     return ($#CODEs,$CODEs[-1]);
                   6349: }
                   6350: 
1.423     albertel 6351: =pod
                   6352: 
                   6353: =item get_codes
                   6354: 
1.424     albertel 6355:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6356:    set of remembered CODEs.
                   6357: 
                   6358:  Arguments:
                   6359:   $old_name - name of the set of remembered CODEs
                   6360:   $cdom     - domain of the course
                   6361:   $cnum     - internal course name
                   6362: 
                   6363:  Returns:
                   6364:   %allcodes - keys are the valid CODEs, values are all 1
                   6365: 
1.423     albertel 6366: =cut
                   6367: 
1.194     albertel 6368: sub get_codes {
1.280     foxr     6369:     my ($old_name, $cdom, $cnum) = @_;
                   6370:     if (!$old_name) {
                   6371: 	$old_name=$env{'form.scantron_CODElist'};
                   6372:     }
                   6373:     if (!$cdom) {
                   6374: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6375:     }
                   6376:     if (!$cnum) {
                   6377: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6378:     }
1.278     albertel 6379:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6380: 				    $cdom,$cnum);
                   6381:     my %allcodes;
                   6382:     if ($result{"type\0$old_name"} eq 'number') {
                   6383: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6384:     } else {
                   6385: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6386:     }
1.194     albertel 6387:     return %allcodes;
                   6388: }
                   6389: 
1.423     albertel 6390: =pod
                   6391: 
                   6392: =item scantron_validate_CODE
                   6393: 
1.424     albertel 6394:    Validates all scanlines in the selected file to not have any
                   6395:    invalid or underspecified CODEs and that none of the codes are
                   6396:    duplicated if this was requested.
                   6397: 
1.423     albertel 6398: =cut
                   6399: 
1.157     albertel 6400: sub scantron_validate_CODE {
                   6401:     my ($r,$currentphase) = @_;
1.257     albertel 6402:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6403:     if ($scantron_config{'CODElocation'} &&
                   6404: 	$scantron_config{'CODEstart'} &&
                   6405: 	$scantron_config{'CODElength'}) {
1.257     albertel 6406: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6407: 	    &FIXME_blow_up()
                   6408: 	}
                   6409:     } else {
                   6410: 	return (0,$currentphase+1);
                   6411:     }
                   6412:     
                   6413:     my %usedCODEs;
                   6414: 
1.194     albertel 6415:     my %allcodes=&get_codes();
1.186     albertel 6416: 
                   6417:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6418:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6419: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6420: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6421: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6422: 						 $scan_data);
                   6423: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6424: 	my $error=0;
1.224     albertel 6425: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6426: 	    &scantron_get_correction($r,$i,$scan_record,
                   6427: 				     \%scantron_config,
                   6428: 				     $line,'incorrectCODE',\%allcodes);
                   6429: 	    return(1,$currentphase);
                   6430: 	}
1.221     albertel 6431: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6432: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6433: 	    &scantron_get_correction($r,$i,$scan_record,
                   6434: 				     \%scantron_config,
1.194     albertel 6435: 				     $line,'incorrectCODE',\%allcodes);
                   6436: 	    return(1,$currentphase);
1.186     albertel 6437: 	}
1.214     albertel 6438: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6439: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6440: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6441: 	    &scantron_get_correction($r,$i,$scan_record,
                   6442: 				     \%scantron_config,
1.194     albertel 6443: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6444: 	    return(1,$currentphase);
1.186     albertel 6445: 	}
1.194     albertel 6446: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6447:     }
1.157     albertel 6448:     return (0,$currentphase+1);
                   6449: }
                   6450: 
1.423     albertel 6451: =pod
                   6452: 
                   6453: =item scantron_validate_doublebubble
                   6454: 
1.424     albertel 6455:    Validates all scanlines in the selected file to not have any
                   6456:    bubble lines with multiple bubbles marked.
                   6457: 
1.423     albertel 6458: =cut
                   6459: 
1.157     albertel 6460: sub scantron_validate_doublebubble {
                   6461:     my ($r,$currentphase) = @_;
                   6462:     #get student info
                   6463:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6464:     my %idmap=&username_to_idmap($classlist);
                   6465: 
                   6466:     #get scantron line setup
1.257     albertel 6467:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6468:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6469:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6470: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6471: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6472: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6473: 						 $scan_data);
                   6474: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6475: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6476: 				 'doublebubble',
                   6477: 				 $$scan_record{'scantron.doubleerror'});
                   6478:     	return (1,$currentphase);
                   6479:     }
                   6480:     return (0,$currentphase+1);
                   6481: }
                   6482: 
1.423     albertel 6483: =pod
                   6484: 
                   6485: =item scantron_get_maxbubble
                   6486: 
1.424     albertel 6487:    Returns the maximum number of bubble lines that are expected to
                   6488:    occur. Does this by walking the selected sequence rendering the
                   6489:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6490:    for what the current value of the problem counter is.
                   6491: 
                   6492:    Caches the result to $env{'form.scantron_maxbubble'}
                   6493: 
1.423     albertel 6494: =cut
                   6495: 
1.330     albertel 6496: sub scantron_get_maxbubble {    
1.257     albertel 6497:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6498: 	$env{'form.scantron_maxbubble'}) {
                   6499: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6500:     }
1.330     albertel 6501: 
1.191     albertel 6502:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6503:     my (undef,undef,$sequence)=
1.257     albertel 6504: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6505: 
1.191     albertel 6506:     my $map=$navmap->getResourceByUrl($sequence);
                   6507:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6508: 
                   6509:     &Apache::lonxml::clear_problem_counter();
                   6510: 
1.191     albertel 6511:     foreach my $resource (@resources) {
1.330     albertel 6512: 	my $result=&Apache::lonnet::ssi($resource->src(),
                   6513: 					('symb' => $resource->symb()));
1.191     albertel 6514:     }
                   6515:     &Apache::lonnet::delenv('scantron\.');
1.330     albertel 6516:     $env{'form.scantron_maxbubble'} =
                   6517: 	&Apache::lonxml::get_problem_counter()-1;
                   6518: 
1.257     albertel 6519:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6520: }
                   6521: 
1.423     albertel 6522: =pod
                   6523: 
                   6524: =item scantron_validate_missingbubbles
                   6525: 
1.424     albertel 6526:    Validates all scanlines in the selected file to not have any
                   6527:    bubble lines with missing bubbles that haven't been verified as missing.
                   6528: 
1.423     albertel 6529: =cut
                   6530: 
1.157     albertel 6531: sub scantron_validate_missingbubbles {
                   6532:     my ($r,$currentphase) = @_;
                   6533:     #get student info
                   6534:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6535:     my %idmap=&username_to_idmap($classlist);
                   6536: 
                   6537:     #get scantron line setup
1.257     albertel 6538:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6539:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6540:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6541:     if (!$max_bubble) { $max_bubble=2**31; }
                   6542:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6543: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6544: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6545: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6546: 						 $scan_data);
                   6547: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6548: 	my @to_correct;
                   6549: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6550: 	    if ($missing > $max_bubble) { next; }
                   6551: 	    push(@to_correct,$missing);
                   6552: 	}
                   6553: 	if (@to_correct) {
                   6554: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6555: 				     $line,'missingbubble',\@to_correct);
                   6556: 	    return (1,$currentphase);
                   6557: 	}
                   6558: 
                   6559:     }
                   6560:     return (0,$currentphase+1);
                   6561: }
                   6562: 
1.423     albertel 6563: =pod
                   6564: 
                   6565: =item scantron_process_students
                   6566: 
                   6567:    Routine that does the actual grading of the bubble sheet information.
                   6568: 
                   6569:    The parsed scanline hash is added to %env 
                   6570: 
                   6571:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6572:    foreach resource , with the form data of
                   6573: 
                   6574: 	'submitted'     =>'scantron' 
                   6575: 	'grade_target'  =>'grade',
                   6576: 	'grade_username'=> username of student
                   6577: 	'grade_domain'  => domain of student
                   6578: 	'grade_courseid'=> of course
                   6579: 	'grade_symb'    => symb of resource to grade
                   6580: 
                   6581:     This triggers a grading pass. The problem grading code takes care
                   6582:     of converting the bubbled letter information (now in %env) into a
                   6583:     valid submission.
                   6584: 
                   6585: =cut
                   6586: 
1.82      albertel 6587: sub scantron_process_students {
1.75      albertel 6588:     my ($r) = @_;
1.257     albertel 6589:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6590:     my ($symb)=&get_symb($r);
1.81      albertel 6591:     if (!$symb) {return '';}
1.324     albertel 6592:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6593: 
1.257     albertel 6594:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6595:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6596:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6597:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6598:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6599:     my $map=$navmap->getResourceByUrl($sequence);
                   6600:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6601: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6602:     my $result= <<SCANTRONFORM;
1.81      albertel 6603: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6604:   <input type="hidden" name="command" value="scantron_configphase" />
                   6605:   $default_form_data
                   6606: SCANTRONFORM
1.82      albertel 6607:     $r->print($result);
                   6608: 
                   6609:     my @delayqueue;
1.140     albertel 6610:     my %completedstudents;
                   6611:     
1.200     albertel 6612:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6613:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6614:  				    'Scantron Progress',$count,
1.195     albertel 6615: 				    'inline',undef,'scantronupload');
1.140     albertel 6616:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6617: 					  'Processing first student');
                   6618:     my $start=&Time::HiRes::time();
1.158     albertel 6619:     my $i=-1;
1.200     albertel 6620:     my ($uname,$udom,$started);
1.157     albertel 6621:     while ($i<$scanlines->{'count'}) {
                   6622:  	($uname,$udom)=('','');
                   6623:  	$i++;
1.200     albertel 6624:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6625:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 6626: 	if ($started) {
                   6627: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   6628: 						     'last student');
                   6629: 	}
                   6630: 	$started=1;
1.157     albertel 6631:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6632:  						 $scan_data);
                   6633:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   6634:  					      \%idmap,$i)) {
                   6635:   	    &scantron_add_delay(\@delayqueue,$line,
                   6636:  				'Unable to find a student that matches',1);
                   6637:  	    next;
                   6638:   	}
                   6639:  	if (exists $completedstudents{$uname}) {
                   6640:  	    &scantron_add_delay(\@delayqueue,$line,
                   6641:  				'Student '.$uname.' has multiple sheets',2);
                   6642:  	    next;
                   6643:  	}
                   6644:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 6645: 
                   6646: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 6647:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 6648: 
                   6649: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   6650: 	    &scantron_putfile($scanlines,$scan_data);
                   6651: 	}
1.161     albertel 6652: 	
                   6653: 	my $i=0;
1.83      albertel 6654: 	foreach my $resource (@resources) {
1.85      albertel 6655: 	    $i++;
1.193     albertel 6656: 	    my %form=('submitted'     =>'scantron',
                   6657: 		      'grade_target'  =>'grade',
                   6658: 		      'grade_username'=>$uname,
                   6659: 		      'grade_domain'  =>$udom,
1.257     albertel 6660: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 6661: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 6662: 	    if (exists($scan_record->{'scantron.CODE'})
                   6663: 		&& 
                   6664: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 6665: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 6666: 	    } else {
                   6667: 		$form{'CODE'}='';
1.193     albertel 6668: 	    }
                   6669: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 6670: 	    if ($result ne '') {
                   6671: 		&Apache::lonnet::logthis("scantron grading error -> $result");
1.257     albertel 6672: 		&Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
1.227     albertel 6673: 	    }
1.213     albertel 6674: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 6675: 	}
1.140     albertel 6676: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 6677: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 6678:     } continue {
1.330     albertel 6679: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 6680: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 6681:     }
1.140     albertel 6682:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 6683: #    my $lasttime = &Time::HiRes::time()-$start;
                   6684: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 6685: 
1.200     albertel 6686:     $r->print("</form>");
1.324     albertel 6687:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 6688:     return '';
1.75      albertel 6689: }
1.157     albertel 6690: 
1.423     albertel 6691: =pod
                   6692: 
                   6693: =item scantron_upload_scantron_data
                   6694: 
                   6695:     Creates the screen for adding a new bubble sheet data file to a course.
                   6696: 
                   6697: =cut
                   6698: 
1.157     albertel 6699: sub scantron_upload_scantron_data {
                   6700:     my ($r)=@_;
1.257     albertel 6701:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 6702:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 6703: 							  'domainid',
                   6704: 							  'coursename');
1.257     albertel 6705:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 6706: 						   'domainid');
1.324     albertel 6707:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 6708:     $r->print(<<UPLOAD);
                   6709: <script type="text/javascript" language="javascript">
                   6710:     function checkUpload(formname) {
                   6711: 	if (formname.upfile.value == "") {
                   6712: 	    alert("Please use the browse button to select a file from your local directory.");
                   6713: 	    return false;
                   6714: 	}
                   6715: 	formname.submit();
                   6716:     }
                   6717: </script>
                   6718: 
                   6719: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 6720: $default_form_data
1.181     albertel 6721: <table>
                   6722: <tr><td>$select_link </td></tr>
                   6723: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   6724: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   6725: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   6726: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   6727: </table>
1.157     albertel 6728: <input name='command' value='scantronupload_save' type='hidden' />
                   6729: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   6730: </form>
                   6731: UPLOAD
                   6732:     return '';
                   6733: }
                   6734: 
1.423     albertel 6735: =pod
                   6736: 
                   6737: =item scantron_upload_scantron_data_save
                   6738: 
                   6739:    Adds a provided bubble information data file to the course if user
                   6740:    has the correct privileges to do so.  
                   6741: 
                   6742: =cut
                   6743: 
1.157     albertel 6744: sub scantron_upload_scantron_data_save {
                   6745:     my($r)=@_;
1.324     albertel 6746:     my ($symb)=&get_symb($r,1);
1.182     albertel 6747:     my $doanotherupload=
                   6748: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   6749: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   6750: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   6751: 	'</form>'."\n";
1.257     albertel 6752:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 6753: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 6754: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 6755: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 6756: 	if ($symb) {
1.324     albertel 6757: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 6758: 	} else {
                   6759: 	    $r->print($doanotherupload);
                   6760: 	}
1.162     albertel 6761: 	return '';
                   6762:     }
1.257     albertel 6763:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       6764:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 6765:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 6766:     #FIXME
                   6767:     #copied from lonnet::userfileupload()
                   6768:     #make that function able to target a specified course
                   6769:     # Replace Windows backslashes by forward slashes
                   6770:     $fname=~s/\\/\//g;
                   6771:     # Get rid of everything but the actual filename
                   6772:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   6773:     # Replace spaces by underscores
                   6774:     $fname=~s/\s+/\_/g;
                   6775:     # Replace all other weird characters by nothing
                   6776:     $fname=~s/[^\w\.\-]//g;
                   6777:     # See if there is anything left
                   6778:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       6779:     my $uploadedfile=$fname;
1.157     albertel 6780:     $fname='scantron_orig_'.$fname;
1.257     albertel 6781:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 6782: 	$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 6783:     } else {
1.275     albertel 6784: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 6785: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 6786: 	    $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 6787: 	} else {
1.398     albertel 6788: 	    $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 6789: 	}
                   6790:     }
1.174     albertel 6791:     if ($symb) {
1.209     ng       6792: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 6793:     } else {
1.182     albertel 6794: 	$r->print($doanotherupload);
1.174     albertel 6795:     }
1.157     albertel 6796:     return '';
                   6797: }
                   6798: 
1.423     albertel 6799: =pod
                   6800: 
                   6801: =item valid_file
                   6802: 
1.424     albertel 6803:    Validates that the requested bubble data file exists in the course.
1.423     albertel 6804: 
                   6805: =cut
                   6806: 
1.202     albertel 6807: sub valid_file {
                   6808:     my ($requested_file)=@_;
                   6809:     foreach my $filename (sort(&scantron_filenames())) {
                   6810: 	if ($requested_file eq $filename) { return 1; }
                   6811:     }
                   6812:     return 0;
                   6813: }
                   6814: 
1.423     albertel 6815: =pod
                   6816: 
                   6817: =item scantron_download_scantron_data
                   6818: 
                   6819:    Shows a list of the three internal files (original, corrected,
                   6820:    skipped) for a specific bubble sheet data file that exists in the
                   6821:    course.
                   6822: 
                   6823: =cut
                   6824: 
1.202     albertel 6825: sub scantron_download_scantron_data {
                   6826:     my ($r)=@_;
1.324     albertel 6827:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 6828:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6829:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6830:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 6831:     if (! &valid_file($file)) {
                   6832: 	$r->print(<<ERROR);
                   6833: 	<p>
                   6834: 	    The requested file name was invalid.
                   6835:         </p>
                   6836: ERROR
1.324     albertel 6837: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 6838: 	return;
                   6839:     }
                   6840:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   6841:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   6842:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   6843:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   6844:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   6845:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   6846:     $r->print(<<DOWNLOAD);
                   6847:     <p>
                   6848: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   6849:     </p>
                   6850:     <p>
                   6851: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   6852:     </p>
                   6853:     <p>
                   6854: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   6855:     </p>
                   6856: DOWNLOAD
1.324     albertel 6857:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 6858:     return '';
                   6859: }
1.157     albertel 6860: 
1.423     albertel 6861: =pod
                   6862: 
                   6863: =back
                   6864: 
                   6865: =cut
                   6866: 
1.75      albertel 6867: #-------- end of section for handling grading scantron forms -------
                   6868: #
                   6869: #-------------------------------------------------------------------
                   6870: 
1.72      ng       6871: #-------------------------- Menu interface -------------------------
                   6872: #
                   6873: #--- Show a Grading Menu button - Calls the next routine ---
                   6874: sub show_grading_menu_form {
1.324     albertel 6875:     my ($symb)=@_;
1.125     ng       6876:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 6877: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 6878: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       6879: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   6880: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   6881: 	'</form>'."\n";
                   6882:     return $result;
                   6883: }
                   6884: 
1.77      ng       6885: # -- Retrieve choices for grading form
                   6886: sub savedState {
                   6887:     my %savedState = ();
1.257     albertel 6888:     if ($env{'form.saveState'}) {
                   6889: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       6890: 	    my ($key,$value) = split(/=/,$_,2);
                   6891: 	    $savedState{$key} = $value;
                   6892: 	}
                   6893:     }
                   6894:     return \%savedState;
                   6895: }
1.76      ng       6896: 
1.72      ng       6897: #--- Displays the main menu page -------
                   6898: sub gradingmenu {
                   6899:     my ($request) = @_;
1.324     albertel 6900:     my ($symb)=&get_symb($request);
1.72      ng       6901:     if (!$symb) {return '';}
1.76      ng       6902:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       6903: 
                   6904:     $request->print(<<GRADINGMENUJS);
                   6905: <script type="text/javascript" language="javascript">
1.116     ng       6906:     function checkChoice(formname,val,cmdx) {
                   6907: 	if (val <= 2) {
                   6908: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       6909: 	    var cmdsave = cmd;
1.116     ng       6910: 	} else {
                   6911: 	    cmd = cmdx;
1.118     ng       6912: 	    cmdsave = 'submission';
1.116     ng       6913: 	}
                   6914: 	formname.command.value = cmd;
1.118     ng       6915: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 6916: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       6917: 	if (val < 5) formname.submit();
                   6918: 	if (val == 5) {
1.72      ng       6919: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   6920: 	    formname.submit();
                   6921: 	}
1.238     albertel 6922: 	if (val < 7) formname.submit();
1.72      ng       6923:     }
                   6924: 
                   6925:     function checkReceiptNo(formname,nospace) {
                   6926: 	var receiptNo = formname.receipt.value;
                   6927: 	var checkOpt = false;
                   6928: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   6929: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   6930: 	if (checkOpt) {
                   6931: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   6932: 	    formname.receipt.value = "";
                   6933: 	    formname.receipt.focus();
                   6934: 	    return false;
                   6935: 	}
                   6936: 	return true;
                   6937:     }
                   6938: </script>
                   6939: GRADINGMENUJS
1.118     ng       6940:     &commonJSfunctions($request);
1.398     albertel 6941:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
1.324     albertel 6942:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       6943:     $result.=$table;
1.76      ng       6944:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       6945:     my $savedState = &savedState();
1.118     ng       6946:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       6947:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       6948:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       6949:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       6950: 
                   6951:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 6952: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       6953: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   6954: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       6955: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       6956: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       6957: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       6958: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   6959: 
1.326     albertel 6960:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   6961: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
1.72      ng       6962: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       6963: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   6964: 
1.326     albertel 6965:     $result.='<table width="100%" border="0">';
1.116     ng       6966:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.167     sakharuk 6967: 	'&nbsp;'.&mt('Select Section').': <select name="section">'."\n";
1.116     ng       6968:     if (ref($sections)) {
1.155     albertel 6969: 	foreach (sort (@$sections)) {
                   6970: 	    $result.='<option value="'.$_.'" '.
1.401     albertel 6971: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
1.155     albertel 6972: 	}
1.116     ng       6973:     }
1.401     albertel 6974:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.116     ng       6975: 
1.401     albertel 6976:     $result.=&mt('Student Status').':'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
1.72      ng       6977: 
1.116     ng       6978:     $result.='</td></tr>';
                   6979: 
1.288     albertel 6980:     $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
1.118     ng       6981: 	'<input type="radio" name="radioChoice" value="submission" '.
1.401     albertel 6982: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 6983: 	'</label> <select name="submitonly">'.
1.145     albertel 6984: 	'<option value="yes" '.
1.401     albertel 6985: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
1.301     albertel 6986: 	'<option value="queued" '.
1.401     albertel 6987: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
1.145     albertel 6988: 	'<option value="graded" '.
1.401     albertel 6989: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 6990: 	'<option value="incorrect" '.
1.401     albertel 6991: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 6992: 	'<option value="all" '.
1.401     albertel 6993: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       6994: 
1.116     ng       6995:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.288     albertel 6996: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.401     albertel 6997: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
1.288     albertel 6998: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       6999: 
1.118     ng       7000:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
1.288     albertel 7001: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.401     albertel 7002: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7003: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       7004: 
1.116     ng       7005:     $result.='<tr bgcolor="#ffffe6"><td><br />'.
1.126     ng       7006: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       7007: 	'</td></tr></table>'."\n";
                   7008: 
                   7009:     $result.='</td><td valign="top">';
                   7010: 
1.326     albertel 7011:     $result.='<table width="100%" border="0">';
1.116     ng       7012:     $result.='<tr bgcolor="#ffffe6"><td>'.
1.184     www      7013: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   7014: 	' '.&mt('scores from file').' </td></tr>'."\n";
1.72      ng       7015: 
1.404     www      7016:     $result.='<tr bgcolor="#ffffe6"><td>'.
                   7017:         '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
                   7018:         ' '.&mt('clicker file').' </td></tr>'."\n";
1.400     www      7019: 
1.75      albertel 7020:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.116     ng       7021: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
1.184     www      7022: 	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
1.75      albertel 7023: 
1.257     albertel 7024:     if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
1.72      ng       7025: 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.184     www      7026: 	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   7027: 	    ' '.&mt('receipt').': '.
1.257     albertel 7028: 	    &Apache::lonnet::recprefix($env{'request.course.id'}).
1.326     albertel 7029: 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
1.72      ng       7030: 	    '</td></tr>'."\n";
                   7031:     } 
1.238     albertel 7032:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7033: 	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   7034: 	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
1.279     albertel 7035:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7036: 	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   7037: 	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
1.44      ng       7038: 
1.401     albertel 7039:     $result.='</table>'."\n".
1.72      ng       7040: 	'</td></tr></table>'."\n".
1.401     albertel 7041: 	'</td></tr></table></form>'."\n";
1.44      ng       7042:     return $result;
1.2       albertel 7043: }
                   7044: 
1.285     albertel 7045: sub reset_perm {
                   7046:     undef(%perm);
                   7047: }
                   7048: 
                   7049: sub init_perm {
                   7050:     &reset_perm();
1.300     albertel 7051:     foreach my $test_perm ('vgr','mgr','opa') {
                   7052: 
                   7053: 	my $scope = $env{'request.course.id'};
                   7054: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7055: 
                   7056: 	    $scope .= '/'.$env{'request.course.sec'};
                   7057: 	    if ( $perm{$test_perm}=
                   7058: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7059: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7060: 	    } else {
                   7061: 		delete($perm{$test_perm});
                   7062: 	    }
1.285     albertel 7063: 	}
                   7064:     }
                   7065: }
                   7066: 
1.400     www      7067: sub gather_clicker_ids {
1.408     albertel 7068:     my %clicker_ids;
1.400     www      7069: 
                   7070:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7071: 
                   7072:     # Set up a couple variables.
1.407     albertel 7073:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7074:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.400     www      7075: 
1.407     albertel 7076:     foreach my $student (keys(%$classlist)) {
1.400     www      7077: 
1.407     albertel 7078:         my $username = $classlist->{$student}->[$username_idx];
                   7079:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7080:         my $clickers =
1.408     albertel 7081: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7082:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7083:             $id=~s/^[\#0]+//;
1.421     www      7084:             $id=~s/[\-\:]//g;
1.407     albertel 7085:             if (exists($clicker_ids{$id})) {
1.408     albertel 7086: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7087:             } else {
1.408     albertel 7088: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7089:             }
                   7090:         }
                   7091:     }
1.407     albertel 7092:     return %clicker_ids;
1.400     www      7093: }
                   7094: 
1.402     www      7095: sub gather_adv_clicker_ids {
1.408     albertel 7096:     my %clicker_ids;
1.402     www      7097:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7098:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7099:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7100:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7101:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7102:             my ($puname,$pudom)=split(/\:/,$person);
                   7103:             my $clickers =
1.408     albertel 7104: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7105:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7106: 		$id=~s/^[\#0]+//;
1.421     www      7107:                 $id=~s/[\-\:]//g;
1.408     albertel 7108: 		if (exists($clicker_ids{$id})) {
                   7109: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7110: 		} else {
                   7111: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7112: 		}
1.405     www      7113:             }
1.402     www      7114:         }
                   7115:     }
1.407     albertel 7116:     return %clicker_ids;
1.402     www      7117: }
                   7118: 
1.413     www      7119: sub clicker_grading_parameters {
                   7120:     return ('gradingmechanism' => 'scalar',
                   7121:             'upfiletype' => 'scalar',
                   7122:             'specificid' => 'scalar',
                   7123:             'pcorrect' => 'scalar',
                   7124:             'pincorrect' => 'scalar');
                   7125: }
                   7126: 
1.400     www      7127: sub process_clicker {
                   7128:     my ($r)=@_;
                   7129:     my ($symb)=&get_symb($r);
                   7130:     if (!$symb) {return '';}
                   7131:     my $result=&checkforfile_js();
                   7132:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7133:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7134:     $result.=$table;
                   7135:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7136:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7137:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7138:         '.</b></td></tr>'."\n";
                   7139:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7140: # Attempt to restore parameters from last session, set defaults if not present
                   7141:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7142:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7143:                                                  \%Saveable_Parameters);
                   7144:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7145:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7146:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7147:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7148: 
                   7149:     my %checked;
                   7150:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7151:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7152:           $checked{$gradingmechanism}="checked='checked'";
                   7153:        }
                   7154:     }
                   7155: 
1.400     www      7156:     my $upload=&mt("Upload File");
                   7157:     my $type=&mt("Type");
1.402     www      7158:     my $attendance=&mt("Award points just for participation");
                   7159:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7160:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7161:     my $pcorrect=&mt("Percentage points for correct solution");
                   7162:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7163:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7164: 						   ('iclicker' => 'i>clicker',
                   7165:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7166:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7167:     $result.=<<ENDUPFORM;
1.402     www      7168: <script type="text/javascript">
                   7169: function sanitycheck() {
                   7170: // Accept only integer percentages
                   7171:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7172:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7173: // Find out grading choice
                   7174:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7175:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7176:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7177:       }
                   7178:    }
                   7179: // By default, new choice equals user selection
                   7180:    newgradingchoice=gradingchoice;
                   7181: // Not good to give more points for false answers than correct ones
                   7182:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7183:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7184:    }
                   7185: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7186:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7187:       document.forms.gradesupload.pcorrect.value=100;
                   7188:       document.forms.gradesupload.pincorrect.value=100;
                   7189:    }
                   7190: // If the values are different, cannot be attendance only
                   7191:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7192:        (gradingchoice=='attendance')) {
                   7193:        newgradingchoice='personnel';
                   7194:    }
                   7195: // Change grading choice to new one
                   7196:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7197:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7198:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7199:       } else {
                   7200:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7201:       }
                   7202:    }
                   7203: // Remember the old state
                   7204:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7205: }
                   7206: </script>
1.400     www      7207: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7208: <input type="hidden" name="symb" value="$symb" />
                   7209: <input type="hidden" name="command" value="processclickerfile" />
                   7210: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7211: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7212: <input type="file" name="upfile" size="50" />
                   7213: <br /><label>$type: $selectform</label>
1.413     www      7214: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
                   7215: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
                   7216: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
1.414     www      7217: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7218: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7219: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7220: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7221: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7222: </form>
                   7223: ENDUPFORM
                   7224:     $result.='</td></tr></table>'."\n".
                   7225:              '</td></tr></table><br /><br />'."\n";
                   7226:     $result.=&show_grading_menu_form($symb);
                   7227:     return $result;
                   7228: }
                   7229: 
                   7230: sub process_clicker_file {
                   7231:     my ($r)=@_;
                   7232:     my ($symb)=&get_symb($r);
                   7233:     if (!$symb) {return '';}
1.413     www      7234: 
                   7235:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7236:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7237:                                               \%Saveable_Parameters);
                   7238: 
1.400     www      7239:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7240:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7241: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7242: 	return $result.&show_grading_menu_form($symb);
1.404     www      7243:     }
1.407     albertel 7244:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7245:     my %correct_ids;
1.404     www      7246:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7247: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7248:     }
                   7249:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7250: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7251: 	   $correct_id=~tr/a-z/A-Z/;
                   7252: 	   $correct_id=~s/\s//gs;
                   7253: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7254:            $correct_id=~s/[\-\:]//g;
1.414     www      7255:            if ($correct_id) {
                   7256: 	      $correct_ids{$correct_id}='specified';
                   7257:            }
                   7258:         }
1.400     www      7259:     }
1.404     www      7260:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7261: 	$result.=&mt('Score based on attendance only');
1.404     www      7262:     } else {
1.408     albertel 7263: 	my $number=0;
1.411     www      7264: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7265: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7266: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7267: 	    if ($correct_ids{$id} eq 'specified') {
                   7268: 		$result.=&mt('specified');
                   7269: 	    } else {
                   7270: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7271: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7272: 	    }
                   7273: 	    $number++;
                   7274: 	}
1.411     www      7275:         $result.="</p>\n";
1.408     albertel 7276: 	if ($number==0) {
                   7277: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7278: 	    return $result.&show_grading_menu_form($symb);
                   7279: 	}
1.404     www      7280:     }
1.405     www      7281:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7282:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7283: 		     '<span class="LC_error">',
                   7284: 		     '</span>',
                   7285: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7286:         return $result.&show_grading_menu_form($symb);
                   7287:     }
1.410     www      7288: 
                   7289: # Were able to get all the info needed, now analyze the file
                   7290: 
1.411     www      7291:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7292:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7293:     my $heading=&mt('Scanning clicker file');
                   7294:     $result.=(<<ENDHEADER);
                   7295: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7296: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7297: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7298: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7299: <input type="hidden" name="symb" value="$symb" />
                   7300: <input type="hidden" name="command" value="assignclickergrades" />
                   7301: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7302: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7303: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7304: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7305: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7306: ENDHEADER
1.408     albertel 7307:     my %responses;
                   7308:     my @questiontitles;
1.405     www      7309:     my $errormsg='';
                   7310:     my $number=0;
                   7311:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7312: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7313:     }
1.419     www      7314:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7315:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7316:     }
1.411     www      7317:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7318:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   7319:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7320:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7321:              '<br />';
1.414     www      7322: # Remember Question Titles
                   7323: # FIXME: Possibly need delimiter other than ":"
                   7324:     for (my $i=0;$i<$number;$i++) {
                   7325:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7326:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7327:     }
1.411     www      7328:     my $correct_count=0;
                   7329:     my $student_count=0;
                   7330:     my $unknown_count=0;
1.414     www      7331: # Match answers with usernames
                   7332: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7333:     foreach my $id (keys(%responses)) {
1.410     www      7334:        if ($correct_ids{$id}) {
1.414     www      7335:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7336:           $correct_count++;
1.410     www      7337:        } elsif ($clicker_ids{$id}) {
                   7338:           $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7339:           $student_count++;
1.410     www      7340:        } else {
1.411     www      7341:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7342:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7343:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7344:                    "\n".&mt("Domain").": ".
                   7345:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7346:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7347:           $unknown_count++;
1.410     www      7348:        }
1.405     www      7349:     }
1.412     www      7350:     $result.='<hr />'.
                   7351:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7352:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7353:        if ($correct_count==0) {
                   7354:           $errormsg.="Found no correct answers answers for grading!";
                   7355:        } elsif ($correct_count>1) {
1.414     www      7356:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7357:        }
                   7358:     }
1.428     www      7359:     if ($number<1) {
                   7360:        $errormsg.="Found no questions.";
                   7361:     }
1.412     www      7362:     if ($errormsg) {
                   7363:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7364:     } else {
                   7365:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7366:     }
                   7367:     $result.='</form></td></tr></table>'."\n".
1.410     www      7368:              '</td></tr></table><br /><br />'."\n";
1.404     www      7369:     return $result.&show_grading_menu_form($symb);
1.400     www      7370: }
                   7371: 
1.405     www      7372: sub iclicker_eval {
1.406     www      7373:     my ($questiontitles,$responses)=@_;
1.405     www      7374:     my $number=0;
                   7375:     my $errormsg='';
                   7376:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7377:         my %components=&Apache::loncommon::record_sep($line);
                   7378:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7379: 	if ($entries[0] eq 'Question') {
                   7380: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7381: 		$$questiontitles[$number]=$entries[$i];
                   7382: 		$number++;
                   7383: 	    }
                   7384: 	}
                   7385: 	if ($entries[0]=~/^\#/) {
                   7386: 	    my $id=$entries[0];
                   7387: 	    my @idresponses;
                   7388: 	    $id=~s/^[\#0]+//;
                   7389: 	    for (my $i=0;$i<$number;$i++) {
                   7390: 		my $idx=3+$i*6;
                   7391: 		push(@idresponses,$entries[$idx]);
                   7392: 	    }
                   7393: 	    $$responses{$id}=join(',',@idresponses);
                   7394: 	}
1.405     www      7395:     }
                   7396:     return ($errormsg,$number);
                   7397: }
                   7398: 
1.419     www      7399: sub interwrite_eval {
                   7400:     my ($questiontitles,$responses)=@_;
                   7401:     my $number=0;
                   7402:     my $errormsg='';
1.420     www      7403:     my $skipline=1;
                   7404:     my $questionnumber=0;
                   7405:     my %idresponses=();
1.419     www      7406:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   7407:         my %components=&Apache::loncommon::record_sep($line);
                   7408:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      7409:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   7410:         if ($entries[1] eq 'Response') { $skipline=1; }
                   7411:         next if $skipline;
                   7412:         if ($entries[0]!=$questionnumber) {
                   7413:            $questionnumber=$entries[0];
                   7414:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   7415:            $number++;
1.419     www      7416:         }
1.420     www      7417:         my $id=$entries[4];
                   7418:         $id=~s/^[\#0]+//;
1.421     www      7419:         $id=~s/^v\d*\://i;
                   7420:         $id=~s/[\-\:]//g;
1.420     www      7421:         $idresponses{$id}[$number]=$entries[6];
                   7422:     }
                   7423:     foreach my $id (keys %idresponses) {
                   7424:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   7425:        $$responses{$id}=~s/^\s*\,//;
1.419     www      7426:     }
                   7427:     return ($errormsg,$number);
                   7428: }
                   7429: 
1.414     www      7430: sub assign_clicker_grades {
                   7431:     my ($r)=@_;
                   7432:     my ($symb)=&get_symb($r);
                   7433:     if (!$symb) {return '';}
1.416     www      7434: # See which part we are saving to
                   7435:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   7436: # FIXME: This should probably look for the first handgradeable part
                   7437:     my $part=$$partlist[0];
                   7438: # Start screen output
1.414     www      7439:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      7440: 
1.414     www      7441:     my $heading=&mt('Assigning grades based on clicker file');
                   7442:     $result.=(<<ENDHEADER);
                   7443: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7444: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7445: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7446: ENDHEADER
                   7447: # Get correct result
                   7448: # FIXME: Possibly need delimiter other than ":"
                   7449:     my @correct=();
1.415     www      7450:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   7451:     my $number=$env{'form.number'};
                   7452:     if ($gradingmechanism ne 'attendance') {
1.414     www      7453:        foreach my $key (keys(%env)) {
                   7454:           if ($key=~/^form\.correct\:/) {
                   7455:              my @input=split(/\,/,$env{$key});
                   7456:              for (my $i=0;$i<=$#input;$i++) {
                   7457:                  if (($correct[$i]) && ($input[$i]) &&
                   7458:                      ($correct[$i] ne $input[$i])) {
                   7459:                     $result.='<br /><span class="LC_warning">'.
                   7460:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   7461:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   7462:                  } elsif ($input[$i]) {
                   7463:                     $correct[$i]=$input[$i];
                   7464:                  }
                   7465:              }
                   7466:           }
                   7467:        }
1.415     www      7468:        for (my $i=0;$i<$number;$i++) {
1.414     www      7469:           if (!$correct[$i]) {
                   7470:              $result.='<br /><span class="LC_error">'.
                   7471:                       &mt('No correct result given for question "[_1]"!',
                   7472:                           $env{'form.question:'.$i}).'</span>';
                   7473:           }
                   7474:        }
                   7475:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   7476:     }
                   7477: # Start grading
1.415     www      7478:     my $pcorrect=$env{'form.pcorrect'};
                   7479:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      7480:     my $storecount=0;
1.415     www      7481:     foreach my $key (keys(%env)) {
1.420     www      7482:        my $user='';
1.415     www      7483:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      7484:           $user=$1;
                   7485:        }
                   7486:        if ($key=~/^form\.unknown\:(.*)$/) {
                   7487:           my $id=$1;
                   7488:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   7489:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
                   7490:           }
                   7491:        }
                   7492:        if ($user) { 
1.415     www      7493:           my @answer=split(/\,/,$env{$key});
                   7494:           my $sum=0;
                   7495:           for (my $i=0;$i<$number;$i++) {
                   7496:              if ($answer[$i]) {
                   7497:                 if ($gradingmechanism eq 'attendance') {
                   7498:                    $sum+=$pcorrect;
                   7499:                 } else {
                   7500:                    if ($answer[$i] eq $correct[$i]) {
                   7501:                       $sum+=$pcorrect;
                   7502:                    } else {
                   7503:                       $sum+=$pincorrect;
                   7504:                    }
                   7505:                 }
                   7506:              }
                   7507:           }
1.416     www      7508:           my $ave=$sum/(100*$number);
                   7509: # Store
                   7510:           my ($username,$domain)=split(/\:/,$user);
                   7511:           my %grades=();
                   7512:           $grades{"resource.$part.solved"}='correct_by_override';
                   7513:           $grades{"resource.$part.awarded"}=$ave;
                   7514:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   7515:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   7516:                                                  $env{'request.course.id'},
                   7517:                                                  $domain,$username);
                   7518:           if ($returncode ne 'ok') {
                   7519:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   7520:           } else {
                   7521:              $storecount++;
                   7522:           }
1.415     www      7523:        }
                   7524:     }
                   7525: # We are done
1.416     www      7526:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   7527:              '</td></tr></table>'."\n".
1.414     www      7528:              '</td></tr></table><br /><br />'."\n";
                   7529:     return $result.&show_grading_menu_form($symb);
                   7530: }
                   7531: 
1.1       albertel 7532: sub handler {
1.41      ng       7533:     my $request=$_[0];
1.102     albertel 7534: 
1.428.2.1! albertel 7535:     &reset_caches();
1.257     albertel 7536:     if ($env{'browser.mathml'}) {
1.141     www      7537: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       7538:     } else {
1.141     www      7539: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       7540:     }
                   7541:     $request->send_http_header;
1.44      ng       7542:     return '' if $request->header_only;
1.41      ng       7543:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 7544:     my $symb=&get_symb($request,1);
1.160     albertel 7545:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   7546:     my $command=$commands[0];
                   7547:     if ($#commands > 0) {
                   7548: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   7549:     }
1.353     albertel 7550:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 7551:     if ($symb eq '' && $command eq '') {
1.257     albertel 7552: 	if ($env{'user.adv'}) {
                   7553: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   7554: 		($env{'form.codethree'})) {
                   7555: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   7556: 		    $env{'form.codethree'};
1.41      ng       7557: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   7558: 		    &Apache::lonnet::checkin($token);
                   7559: 		if ($tsymb) {
1.137     albertel 7560: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       7561: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 7562: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   7563: 					  ('grade_username' => $tuname,
                   7564: 					   'grade_domain' => $tudom,
                   7565: 					   'grade_courseid' => $tcrsid,
                   7566: 					   'grade_symb' => $tsymb)));
1.41      ng       7567: 		    } else {
1.45      ng       7568: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 7569: 		    }
1.41      ng       7570: 		} else {
1.45      ng       7571: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       7572: 		}
1.14      www      7573: 	    } else {
1.41      ng       7574: 		$request->print(&Apache::lonxml::tokeninputfield());
                   7575: 	    }
                   7576: 	}
                   7577:     } else {
1.285     albertel 7578: 	&init_perm();
1.104     albertel 7579: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 7580: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 7581: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       7582: 	    &pickStudentPage($request);
1.103     albertel 7583: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       7584: 	    &displayPage($request);
1.104     albertel 7585: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       7586: 	    &updateGradeByPage($request);
1.104     albertel 7587: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       7588: 	    &processGroup($request);
1.104     albertel 7589: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.41      ng       7590: 	    $request->print(&gradingmenu($request));
1.104     albertel 7591: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       7592: 	    $request->print(&viewgrades($request));
1.104     albertel 7593: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       7594: 	    $request->print(&processHandGrade($request));
1.106     albertel 7595: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       7596: 	    $request->print(&editgrades($request));
1.106     albertel 7597: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       7598: 	    $request->print(&verifyreceipt($request));
1.400     www      7599:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   7600:             $request->print(&process_clicker($request));
                   7601:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   7602:             $request->print(&process_clicker_file($request));
1.414     www      7603:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   7604:             $request->print(&assign_clicker_grades($request));
1.106     albertel 7605: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       7606: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 7607: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       7608: 	    $request->print(&csvupload($request));
1.106     albertel 7609: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       7610: 	    $request->print(&csvuploadmap($request));
1.246     albertel 7611: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 7612: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 7613: 		$request->print(&csvuploadoptions($request));
1.41      ng       7614: 	    } else {
1.257     albertel 7615: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   7616: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       7617: 		} else {
1.257     albertel 7618: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       7619: 		}
                   7620: 		$request->print(&csvuploadmap($request));
                   7621: 	    }
1.246     albertel 7622: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   7623: 	    $request->print(&csvuploadassign($request));
1.106     albertel 7624: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 7625: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 7626:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   7627:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 7628: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   7629: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 7630: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 7631: 	    $request->print(&scantron_process_students($request));
1.157     albertel 7632:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 7633:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   7634: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 7635:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 7636:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 7637:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   7638: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 7639:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 7640:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 7641: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 7642:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 7643: 	} elsif ($command) {
1.157     albertel 7644: 	    $request->print("Access Denied ($command)");
1.26      albertel 7645: 	}
1.2       albertel 7646:     }
1.353     albertel 7647:     $request->print(&Apache::loncommon::end_page());
1.428.2.1! albertel 7648:     &reset_caches();
1.44      ng       7649:     return '';
                   7650: }
                   7651: 
1.1       albertel 7652: 1;
                   7653: 
1.13      albertel 7654: __END__;

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