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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.434   ! albertel    4: # $Id: grades.pm,v 1.433 2007/08/22 18:27:03 banghart 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.434   ! 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.434   ! albertel  197: sub reset_caches {
        !           198:     &reset_analyze_cache();
        !           199:     &reset_perm();
        !           200: }
        !           201: 
        !           202: {
        !           203:     my %analyze_cache;
1.148     albertel  204: 
1.434   ! albertel  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.434   ! 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.434   ! 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.434   ! 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.267     albertel  758:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
                    759: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
                    760: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
1.348     bowersj2  761: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
                    762:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
                    763:         '<option value="1">Whole Points</option>'.
                    764:         '<option value=".5">Half Points</option>'.
1.349     albertel  765:         '<option value=".25">Quarter Points</option>'.
                    766:         '<option value=".1">Tenths of a Point</option>'.
1.348     bowersj2  767:         '</select>'.
1.432     banghart  768:         &build_section_inputs().
1.45      ng        769: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  770: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    771: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    772: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    773: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  774: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        775: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    776: 
1.257     albertel  777:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
                    778: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng        779:     } else {
                    780: 	$gradeTable.='<b>Student Status:</b> '.
                    781: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
                    782:     }
1.112     ng        783: 
1.126     ng        784:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    785: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
1.110     ng        786: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  787: 
                    788: # checkall buttons
                    789:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        790:     $gradeTable.='<input type="button" '."\n".
1.45      ng        791: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.249     albertel  792: 	'value="Next->" /> <br />'."\n";
                    793:     $gradeTable.=&check_buttons();
1.401     albertel  794:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
1.249     albertel  795:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
1.45      ng        796:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
1.110     ng        797: 	'<table border="0"><tr bgcolor="#e6ffff">';
                    798:     my $loop = 0;
                    799:     while ($loop < 2) {
1.126     ng        800: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
1.250     albertel  801: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
1.301     albertel  802: 	if ($env{'form.showgrading'} eq 'yes' 
                    803: 	    && $submitonly ne 'queued'
                    804: 	    && $submitonly ne 'all') {
1.110     ng        805: 	    foreach (sort(@$partlist)) {
1.324     albertel  806: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
1.207     albertel  807: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
                    808: 		    ' Status&nbsp;</b></td>';
1.110     ng        809: 	    }
1.301     albertel  810: 	} elsif ($submitonly eq 'queued') {
                    811: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
1.110     ng        812: 	}
                    813: 	$loop++;
1.126     ng        814: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        815:     }
1.45      ng        816:     $gradeTable.='</tr>'."\n";
1.41      ng        817: 
1.45      ng        818:     my $ctr = 0;
1.294     albertel  819:     foreach my $student (sort 
                    820: 			 {
                    821: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    822: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    823: 			     }
                    824: 			     return $a cmp $b;
                    825: 			 }
                    826: 			 (keys(%$fullname))) {
1.41      ng        827: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  828: 
1.110     ng        829: 	my %status = ();
1.301     albertel  830: 
                    831: 	if ($submitonly eq 'queued') {
                    832: 	    my %queue_status = 
                    833: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    834: 							$udom,$uname);
                    835: 	    next if (!defined($queue_status{'gradingqueue'}));
                    836: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    837: 	}
                    838: 
                    839: 	if ($env{'form.showgrading'} eq 'yes' 
                    840: 	    && $submitonly ne 'queued'
                    841: 	    && $submitonly ne 'all') {
1.324     albertel  842: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  843: 	    my $submitted = 0;
1.164     albertel  844: 	    my $graded = 0;
1.248     albertel  845: 	    my $incorrect = 0;
1.110     ng        846: 	    foreach (keys(%status)) {
1.145     albertel  847: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  848: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    849: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    850: 		
1.110     ng        851: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    852: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  853: 		    $submitted = 0;
1.150     albertel  854: 		    my ($part)=split(/\./,$partid);
1.110     ng        855: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  856: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        857: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    858: 		}
1.41      ng        859: 	    }
1.248     albertel  860: 	    
1.156     albertel  861: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    862: 				     $submitonly eq 'incorrect' ||
                    863: 				     $submitonly eq 'graded'));
1.248     albertel  864: 	    next if (!$graded && ($submitonly eq 'graded'));
                    865: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        866: 	}
1.34      ng        867: 
1.45      ng        868: 	$ctr++;
1.249     albertel  869: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    870: 
1.104     albertel  871: 	if ( $perm{'vgr'} eq 'F' ) {
1.110     ng        872: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
1.126     ng        873: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  874:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    875:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    876: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    877: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
                    878: 	       '&nbsp;'.$section.'</td>'."\n";
1.110     ng        879: 
1.257     albertel  880: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        881: 		foreach (sort keys(%status)) {
                    882: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  883: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        884: 		}
1.41      ng        885: 	    }
1.126     ng        886: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.110     ng        887: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
1.41      ng        888: 	}
                    889:     }
1.110     ng        890:     if ($ctr%2 ==1) {
1.126     ng        891: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel  892: 	    if ($env{'form.showgrading'} eq 'yes' 
                    893: 		&& $submitonly ne 'queued'
                    894: 		&& $submitonly ne 'all') {
1.110     ng        895: 		foreach (@$partlist) {
                    896: 		    $gradeTable.='<td>&nbsp;</td>';
                    897: 		}
1.301     albertel  898: 	    } elsif ($submitonly eq 'queued') {
                    899: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng        900: 	    }
                    901: 	$gradeTable.='</tr>';
                    902:     }
                    903: 
1.249     albertel  904:     $gradeTable.='</table></td></tr></table>'."\n".
1.45      ng        905: 	'<input type="button" '.
                    906: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng        907: 	'value="Next->" /></form>'."\n";
1.45      ng        908:     if ($ctr == 0) {
1.96      albertel  909: 	my $num_students=(scalar(keys(%$fullname)));
                    910: 	if ($num_students eq 0) {
1.398     albertel  911: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel  912: 	} else {
1.171     albertel  913: 	    my $submissions='submissions';
                    914: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                    915: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel  916: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel  917: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel  918: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel  919: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel  920: 	}
1.46      ng        921:     } elsif ($ctr == 1) {
                    922: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
1.45      ng        923:     }
1.324     albertel  924:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng        925:     $request->print($gradeTable);
1.44      ng        926:     return '';
1.10      ng        927: }
                    928: 
1.44      ng        929: #---- Called from the listStudents routine
1.249     albertel  930: 
                    931: sub check_script {
                    932:     my ($form, $type)=@_;
                    933:     my $chkallscript='<script type="text/javascript">
                    934:     function checkall() {
                    935:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    936:             ele = document.forms.'.$form.'.elements[i];
                    937:             if (ele.name == "'.$type.'") {
                    938:             document.forms.'.$form.'.elements[i].checked=true;
                    939:                                        }
                    940:         }
                    941:     }
                    942: 
                    943:     function checksec() {
                    944:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    945:             ele = document.forms.'.$form.'.elements[i];
                    946:            string = document.forms.'.$form.'.chksec.value;
                    947:            if
                    948:           (ele.value.indexOf(":::SECTION"+string)>0) {
                    949:               document.forms.'.$form.'.elements[i].checked=true;
                    950:             }
                    951:         }
                    952:     }
                    953: 
                    954: 
                    955:     function uncheckall() {
                    956:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    957:             ele = document.forms.'.$form.'.elements[i];
                    958:             if (ele.name == "'.$type.'") {
                    959:             document.forms.'.$form.'.elements[i].checked=false;
                    960:                                        }
                    961:         }
                    962:     }
                    963: 
                    964: </script>'."\n";
                    965:     return $chkallscript;
                    966: }
                    967: 
                    968: sub check_buttons {
                    969:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                    970:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                    971:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                    972:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                    973:     return $buttons;
                    974: }
                    975: 
1.44      ng        976: #     Displays the submissions for one student or a group of students
1.34      ng        977: sub processGroup {
1.41      ng        978:     my ($request)  = shift;
                    979:     my $ctr        = 0;
1.155     albertel  980:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng        981:     my $total      = scalar(@stuchecked)-1;
1.45      ng        982: 
1.396     banghart  983:     foreach my $student (@stuchecked) {
                    984: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel  985: 	$env{'form.student'}        = $uname;
                    986: 	$env{'form.userdom'}        = $udom;
                    987: 	$env{'form.fullname'}       = $fullname;
1.41      ng        988: 	&submission($request,$ctr,$total);
                    989: 	$ctr++;
                    990:     }
                    991:     return '';
1.35      ng        992: }
1.34      ng        993: 
1.44      ng        994: #------------------------------------------------------------------------------------
                    995: #
                    996: #-------------------------- Next few routines handles grading by student, essentially
                    997: #                           handles essay response type problem/part
                    998: #
                    999: #--- Javascript to handle the submission page functionality ---
                   1000: sub sub_page_js {
                   1001:     my $request = shift;
                   1002:     $request->print(<<SUBJAVASCRIPT);
                   1003: <script type="text/javascript" language="javascript">
1.71      ng       1004:     function updateRadio(formname,id,weight) {
1.125     ng       1005: 	var gradeBox = formname["GD_BOX"+id];
                   1006: 	var radioButton = formname["RADVAL"+id];
                   1007: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1008: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1009: 	gradeBox.value = pts;
                   1010: 	var resetbox = false;
                   1011: 	if (isNaN(pts) || pts < 0) {
                   1012: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1013: 	    for (var i=0; i<radioButton.length; i++) {
                   1014: 		if (radioButton[i].checked) {
                   1015: 		    gradeBox.value = i;
                   1016: 		    resetbox = true;
                   1017: 		}
                   1018: 	    }
                   1019: 	    if (!resetbox) {
                   1020: 		formtextbox.value = "";
                   1021: 	    }
                   1022: 	    return;
1.44      ng       1023: 	}
1.71      ng       1024: 
                   1025: 	if (pts > weight) {
                   1026: 	    var resp = confirm("You entered a value ("+pts+
                   1027: 			       ") greater than the weight for the part. Accept?");
                   1028: 	    if (resp == false) {
1.125     ng       1029: 		gradeBox.value = oldpts;
1.71      ng       1030: 		return;
                   1031: 	    }
1.44      ng       1032: 	}
1.13      albertel 1033: 
1.71      ng       1034: 	for (var i=0; i<radioButton.length; i++) {
                   1035: 	    radioButton[i].checked=false;
                   1036: 	    if (pts == i && pts != "") {
                   1037: 		radioButton[i].checked=true;
                   1038: 	    }
                   1039: 	}
                   1040: 	updateSelect(formname,id);
1.125     ng       1041: 	formname["stores"+id].value = "0";
1.41      ng       1042:     }
1.5       albertel 1043: 
1.72      ng       1044:     function writeBox(formname,id,pts) {
1.125     ng       1045: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1046: 	if (checkSolved(formname,id) == 'update') {
                   1047: 	    gradeBox.value = pts;
                   1048: 	} else {
1.125     ng       1049: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1050: 	    gradeBox.value = oldpts;
1.125     ng       1051: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1052: 	    for (var i=0; i<radioButton.length; i++) {
                   1053: 		radioButton[i].checked=false;
1.72      ng       1054: 		if (i == oldpts) {
1.71      ng       1055: 		    radioButton[i].checked=true;
                   1056: 		}
                   1057: 	    }
1.41      ng       1058: 	}
1.125     ng       1059: 	formname["stores"+id].value = "0";
1.71      ng       1060: 	updateSelect(formname,id);
                   1061: 	return;
1.41      ng       1062:     }
1.44      ng       1063: 
1.71      ng       1064:     function clearRadBox(formname,id) {
                   1065: 	if (checkSolved(formname,id) == 'noupdate') {
                   1066: 	    updateSelect(formname,id);
                   1067: 	    return;
                   1068: 	}
1.125     ng       1069: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1070: 	for (var i=0; i<gradeSelect.length; i++) {
                   1071: 	    if (gradeSelect[i].selected) {
                   1072: 		var selectx=i;
                   1073: 	    }
                   1074: 	}
1.125     ng       1075: 	var stores = formname["stores"+id];
1.71      ng       1076: 	if (selectx == stores.value) { return };
1.125     ng       1077: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1078: 	gradeBox.value = "";
1.125     ng       1079: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1080: 	for (var i=0; i<radioButton.length; i++) {
                   1081: 	    radioButton[i].checked=false;
                   1082: 	}
                   1083: 	stores.value = selectx;
                   1084:     }
1.5       albertel 1085: 
1.71      ng       1086:     function checkSolved(formname,id) {
1.125     ng       1087: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1088: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1089: 	    if (!reply) {return "noupdate";}
1.120     ng       1090: 	    formname.overRideScore.value = 'yes';
1.41      ng       1091: 	}
1.71      ng       1092: 	return "update";
1.13      albertel 1093:     }
1.71      ng       1094: 
                   1095:     function updateSelect(formname,id) {
1.125     ng       1096: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1097: 	return;
1.41      ng       1098:     }
1.33      ng       1099: 
1.121     ng       1100: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1101:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1102: 	formname.gradeOpt.value = val;
1.71      ng       1103: 	if (val == "Save & Next") {
                   1104: 	    for (i=0;i<=total;i++) {
                   1105: 		for (j=0;j<parttot;j++) {
1.125     ng       1106: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1107: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1108: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1109: 			if (points == "") {
1.125     ng       1110: 			    var name = formname["name"+i].value;
1.129     ng       1111: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1112: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1113: 					       ", part "+partid+". Continue?");
1.71      ng       1114: 			    if (resp == false) {
1.125     ng       1115: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1116: 				return false;
                   1117: 			    }
                   1118: 			}
                   1119: 		    }
                   1120: 		    
                   1121: 		}
                   1122: 	    }
                   1123: 	    
                   1124: 	}
1.121     ng       1125: 	if (val == "Grade Student") {
                   1126: 	    formname.showgrading.value = "yes";
                   1127: 	    if (formname.Status.value == "") {
                   1128: 		formname.Status.value = "Active";
                   1129: 	    }
                   1130: 	    formname.studentNo.value = total;
                   1131: 	}
1.120     ng       1132: 	formname.submit();
                   1133:     }
                   1134: 
1.71      ng       1135: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1136:     function checkSubmitPage(formname,total) {
                   1137: 	noscore = new Array(100);
                   1138: 	var ptr = 0;
                   1139: 	for (i=1;i<total;i++) {
1.125     ng       1140: 	    var partid = formname["q_"+i].value;
1.127     ng       1141: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1142: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1143: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1144: 		if (points == "" && status != "correct_by_student") {
                   1145: 		    noscore[ptr] = i;
                   1146: 		    ptr++;
                   1147: 		}
                   1148: 	    }
                   1149: 	}
                   1150: 	if (ptr != 0) {
                   1151: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1152: 	    var prolist = "";
                   1153: 	    if (ptr == 1) {
                   1154: 		prolist = noscore[0];
                   1155: 	    } else {
                   1156: 		var i = 0;
                   1157: 		while (i < ptr-1) {
                   1158: 		    prolist += noscore[i]+", ";
                   1159: 		    i++;
                   1160: 		}
                   1161: 		prolist += "and "+noscore[i];
                   1162: 	    }
                   1163: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1164: 	    if (resp == false) {
                   1165: 		return false;
                   1166: 	    }
                   1167: 	}
1.45      ng       1168: 
1.71      ng       1169: 	formname.submit();
                   1170:     }
                   1171: </script>
                   1172: SUBJAVASCRIPT
                   1173: }
1.45      ng       1174: 
1.71      ng       1175: #--- javascript for essay type problem --
                   1176: sub sub_page_kw_js {
                   1177:     my $request = shift;
1.80      ng       1178:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1179:     &commonJSfunctions($request);
1.350     albertel 1180: 
1.351     albertel 1181:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1182:     <script text="text/javascript">
                   1183:     function checkInput() {
                   1184:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1185:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1186:       var usrctr = document.msgcenter.usrctr.value;
                   1187:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1188:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1189: 
                   1190:       var msgchk = "";
                   1191:       if (document.msgcenter.subchk.checked) {
                   1192:          msgchk = "msgsub,";
                   1193:       }
                   1194:       var includemsg = 0;
                   1195:       for (var i=1; i<=nmsg; i++) {
                   1196:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1197:           var frmmsg = document.msgcenter["msg"+i];
                   1198:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1199:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1200:           showflg.value = "1";
                   1201:           var chkbox = document.msgcenter["msgn"+i];
                   1202:           if (chkbox.checked) {
                   1203:              msgchk += "savemsg"+i+",";
                   1204:              includemsg = 1;
                   1205:           }
                   1206:       }
                   1207:       if (document.msgcenter.newmsgchk.checked) {
                   1208:          msgchk += "newmsg"+usrctr;
                   1209:          includemsg = 1;
                   1210:       }
                   1211:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1212:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1213:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1214:       includemsg.value = msgchk;
                   1215: 
                   1216:       self.close()
                   1217: 
                   1218:     }
                   1219:     </script>
                   1220: INNERJS
                   1221: 
1.351     albertel 1222:     my $inner_js_highlight_central=<<INNERJS;
                   1223:  <script type="text/javascript">
                   1224:     function updateChoice(flag) {
                   1225:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1226:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1227:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1228:       opener.document.SCORE.refresh.value = "on";
                   1229:       if (opener.document.SCORE.keywords.value!=""){
                   1230:          opener.document.SCORE.submit();
                   1231:       }
                   1232:       self.close()
                   1233:     }
                   1234: </script>
                   1235: INNERJS
                   1236: 
                   1237:     my $start_page_msg_central = 
                   1238:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1239: 				       {'js_ready'  => 1,
                   1240: 					'only_body' => 1,
                   1241: 					'bgcolor'   =>'#FFFFFF',});
                   1242:     my $end_page_msg_central = 
                   1243: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1244: 
                   1245: 
                   1246:     my $start_page_highlight_central = 
                   1247:         &Apache::loncommon::start_page('Highlight Central',
                   1248: 				       $inner_js_highlight_central,
1.350     albertel 1249: 				       {'js_ready'  => 1,
                   1250: 					'only_body' => 1,
                   1251: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1252:     my $end_page_highlight_central = 
1.350     albertel 1253: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1254: 
1.219     www      1255:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1256:     $docopen=~s/^document\.//;
1.71      ng       1257:     $request->print(<<SUBJAVASCRIPT);
                   1258: <script type="text/javascript" language="javascript">
1.45      ng       1259: 
1.44      ng       1260: //===================== Show list of keywords ====================
1.122     ng       1261:   function keywords(formname) {
                   1262:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1263:     if (nret==null) return;
1.122     ng       1264:     formname.keywords.value = nret;
1.44      ng       1265: 
1.122     ng       1266:     if (formname.keywords.value != "") {
1.128     ng       1267: 	formname.refresh.value = "on";
1.122     ng       1268: 	formname.submit();
1.44      ng       1269:     }
                   1270:     return;
                   1271:   }
                   1272: 
                   1273: //===================== Script to view submitted by ==================
                   1274:   function viewSubmitter(submitter) {
                   1275:     document.SCORE.refresh.value = "on";
                   1276:     document.SCORE.NCT.value = "1";
                   1277:     document.SCORE.unamedom0.value = submitter;
                   1278:     document.SCORE.submit();
                   1279:     return;
                   1280:   }
                   1281: 
                   1282: //===================== Script to add keyword(s) ==================
                   1283:   function getSel() {
                   1284:     if (document.getSelection) txt = document.getSelection();
                   1285:     else if (document.selection) txt = document.selection.createRange().text;
                   1286:     else return;
                   1287:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1288:     if (cleantxt=="") {
1.46      ng       1289: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1290: 	return;
                   1291:     }
                   1292:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1293:     if (nret==null) return;
1.127     ng       1294:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1295:     if (document.SCORE.keywords.value != "") {
1.127     ng       1296: 	document.SCORE.refresh.value = "on";
1.44      ng       1297: 	document.SCORE.submit();
                   1298:     }
                   1299:     return;
                   1300:   }
                   1301: 
                   1302: //====================== Script for composing message ==============
1.80      ng       1303:    // preload images
                   1304:    img1 = new Image();
                   1305:    img1.src = "$iconpath/mailbkgrd.gif";
                   1306:    img2 = new Image();
                   1307:    img2.src = "$iconpath/mailto.gif";
                   1308: 
1.44      ng       1309:   function msgCenter(msgform,usrctr,fullname) {
                   1310:     var Nmsg  = msgform.savemsgN.value;
                   1311:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1312:     var subject = msgform.msgsub.value;
1.127     ng       1313:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1314:     re = /msgsub/;
                   1315:     var shwsel = "";
                   1316:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1317:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1318:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1319:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1320: 	var testmsg = "savemsg"+i+",";
                   1321: 	re = new RegExp(testmsg,"g");
1.44      ng       1322: 	shwsel = "";
                   1323: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1324: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1325: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1326: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1327: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1328:     }
1.125     ng       1329:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1330:     shwsel = "";
                   1331:     re = /newmsg/;
                   1332:     if (re.test(msgchk)) { shwsel = "checked" }
                   1333:     newMsg(newmsg,shwsel);
                   1334:     msgTail(); 
                   1335:     return;
                   1336:   }
                   1337: 
1.123     ng       1338:   function checkEntities(strx) {
                   1339:     if (strx.length == 0) return strx;
                   1340:     var orgStr = ["&", "<", ">", '"']; 
                   1341:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1342:     var counter = 0;
                   1343:     while (counter < 4) {
                   1344: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1345: 	counter++;
                   1346:     }
                   1347:     return strx;
                   1348:   }
                   1349: 
                   1350:   function strReplace(strx, orgStr, newStr) {
                   1351:     return strx.split(orgStr).join(newStr);
                   1352:   }
                   1353: 
1.44      ng       1354:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1355:     var height = 70*Nmsg+250;
1.44      ng       1356:     var scrollbar = "no";
                   1357:     if (height > 600) {
                   1358: 	height = 600;
                   1359: 	scrollbar = "yes";
                   1360:     }
1.118     ng       1361:     var xpos = (screen.width-600)/2;
                   1362:     xpos = (xpos < 0) ? '0' : xpos;
                   1363:     var ypos = (screen.height-height)/2-30;
                   1364:     ypos = (ypos < 0) ? '0' : ypos;
                   1365: 
1.206     albertel 1366:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1367:     pWin.focus();
                   1368:     pDoc = pWin.document;
1.219     www      1369:     pDoc.$docopen;
1.351     albertel 1370:     pDoc.write('$start_page_msg_central');
1.76      ng       1371: 
                   1372:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1373:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.398     albertel 1374:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
1.76      ng       1375: 
                   1376:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1377:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1378:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1.44      ng       1379: }
                   1380:     function displaySubject(msg,shwsel) {
1.76      ng       1381:     pDoc = pWin.document;
                   1382:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1383:     pDoc.write("<td>Subject</td>");
                   1384:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1385:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1.44      ng       1386: }
                   1387: 
1.72      ng       1388:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1389:     pDoc = pWin.document;
                   1390:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1391:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
                   1392:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1393:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1.44      ng       1394: }
                   1395: 
                   1396:   function newMsg(newmsg,shwsel) {
1.76      ng       1397:     pDoc = pWin.document;
                   1398:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1399:     pDoc.write("<td align=\\"center\\">New</td>");
                   1400:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1401:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1.44      ng       1402: }
                   1403: 
                   1404:   function msgTail() {
1.76      ng       1405:     pDoc = pWin.document;
                   1406:     pDoc.write("</table>");
                   1407:     pDoc.write("</td></tr></table>&nbsp;");
                   1408:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1409:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1410:     pDoc.write("</form>");
1.351     albertel 1411:     pDoc.write('$end_page_msg_central');
1.128     ng       1412:     pDoc.close();
1.44      ng       1413: }
                   1414: 
                   1415: //====================== Script for keyword highlight options ==============
                   1416:   function kwhighlight() {
                   1417:     var kwclr    = document.SCORE.kwclr.value;
                   1418:     var kwsize   = document.SCORE.kwsize.value;
                   1419:     var kwstyle  = document.SCORE.kwstyle.value;
                   1420:     var redsel = "";
                   1421:     var grnsel = "";
                   1422:     var blusel = "";
                   1423:     if (kwclr=="red")   {var redsel="checked"};
                   1424:     if (kwclr=="green") {var grnsel="checked"};
                   1425:     if (kwclr=="blue")  {var blusel="checked"};
                   1426:     var sznsel = "";
                   1427:     var sz1sel = "";
                   1428:     var sz2sel = "";
                   1429:     if (kwsize=="0")  {var sznsel="checked"};
                   1430:     if (kwsize=="+1") {var sz1sel="checked"};
                   1431:     if (kwsize=="+2") {var sz2sel="checked"};
                   1432:     var synsel = "";
                   1433:     var syisel = "";
                   1434:     var sybsel = "";
                   1435:     if (kwstyle=="")    {var synsel="checked"};
                   1436:     if (kwstyle=="<i>") {var syisel="checked"};
                   1437:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1438:     highlightCentral();
                   1439:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1440:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1441:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1442:     highlightend();
                   1443:     return;
                   1444:   }
                   1445: 
                   1446:   function highlightCentral() {
1.76      ng       1447: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1448:     var xpos = (screen.width-400)/2;
                   1449:     xpos = (xpos < 0) ? '0' : xpos;
                   1450:     var ypos = (screen.height-330)/2-30;
                   1451:     ypos = (ypos < 0) ? '0' : ypos;
                   1452: 
1.206     albertel 1453:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1454:     hwdWin.focus();
                   1455:     var hDoc = hwdWin.document;
1.219     www      1456:     hDoc.$docopen;
1.351     albertel 1457:     hDoc.write('$start_page_highlight_central');
1.76      ng       1458:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.398     albertel 1459:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
1.76      ng       1460: 
                   1461:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1462:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1463:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1.44      ng       1464:   }
                   1465: 
                   1466:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1467:     var hDoc = hwdWin.document;
                   1468:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1469:     hDoc.write("<td align=\\"left\\">");
                   1470:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
                   1471:     hDoc.write("<td align=\\"left\\">");
                   1472:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
                   1473:     hDoc.write("<td align=\\"left\\">");
                   1474:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
                   1475:     hDoc.write("</tr>");
1.44      ng       1476:   }
                   1477: 
                   1478:   function highlightend() { 
1.76      ng       1479:     var hDoc = hwdWin.document;
                   1480:     hDoc.write("</table>");
                   1481:     hDoc.write("</td></tr></table>&nbsp;");
                   1482:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1483:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1484:     hDoc.write("</form>");
1.351     albertel 1485:     hDoc.write('$end_page_highlight_central');
1.128     ng       1486:     hDoc.close();
1.44      ng       1487:   }
                   1488: 
                   1489: </script>
                   1490: SUBJAVASCRIPT
                   1491: }
                   1492: 
1.349     albertel 1493: sub get_increment {
1.348     bowersj2 1494:     my $increment = $env{'form.increment'};
                   1495:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1496:         $increment != .1) {
                   1497:         $increment = 1;
                   1498:     }
                   1499:     return $increment;
                   1500: }
                   1501: 
1.71      ng       1502: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1503: sub gradeBox {
1.322     albertel 1504:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1505:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1506: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1507: 	'/check.gif" height="16" border="0" />';
                   1508:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
                   1509:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
1.398     albertel 1510: 		  '<span class="LC_info">problem weight assigned by computer</span>');
1.71      ng       1511:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1512:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1513: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1514:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.324     albertel 1515:     my $display_part=&get_display_part($partid,$symb);
1.270     albertel 1516:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1517: 				       [$partid]);
                   1518:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1519:     if ($last_resets{$partid}) {
                   1520:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1521:     }
1.71      ng       1522:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1523: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1524:     my $ctr = 0;
1.348     bowersj2 1525:     my $thisweight = 0;
1.349     albertel 1526:     my $increment = &get_increment();
1.71      ng       1527:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1528:     while ($thisweight<=$wgt) {
1.381     albertel 1529: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1530: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1531: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1532: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1533: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1534:         $thisweight += $increment;
1.71      ng       1535: 	$ctr++;
                   1536:     }
                   1537:     $result.='</tr></table>';
                   1538:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1539:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1540: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1541: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1542: 	$wgt.')" /></td>'."\n";
                   1543:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1544: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1545: 	' </td><td>'."\n";
                   1546:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1547: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1548:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1549: 	$result.='<option></option>'.
1.401     albertel 1550: 	    '<option selected="selected">excused</option>';
1.71      ng       1551:     } else {
1.401     albertel 1552: 	$result.='<option selected="selected"></option>'.
1.125     ng       1553: 	    '<option>excused</option>';
1.71      ng       1554:     }
1.125     ng       1555:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1556:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1557:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1558: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1559: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1560: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1561:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1562:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1563:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1564:         $aggtries.'" />'."\n";
1.71      ng       1565:     $result.='</td></tr></table>'."\n";
1.323     banghart 1566:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1567:     return $result;
                   1568: }
1.322     albertel 1569: 
                   1570: sub handback_box {
1.323     banghart 1571:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1572:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1573:     my (@respids);
1.375     albertel 1574:      my @part_response_id = &flatten_responseType($responseType);
                   1575:     foreach my $part_response_id (@part_response_id) {
                   1576:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1577:         if ($part eq $partid) {
1.375     albertel 1578:             push(@respids,$resp);
1.323     banghart 1579:         }
                   1580:     }
1.318     banghart 1581:     my $result;
1.323     banghart 1582:     foreach my $respid (@respids) {
1.322     albertel 1583: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1584: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1585: 	next if (!@$files);
                   1586: 	my $file_counter = 1;
1.313     banghart 1587: 	foreach my $file (@$files) {
1.368     banghart 1588: 	    if ($file =~ /\/portfolio\//) {
                   1589:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1590:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1591:     	        $file_disp = "$name.$ext";
                   1592:     	        $file = $file_path.$file_disp;
                   1593:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1594:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1595:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1596:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.369     banghart 1597:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1.368     banghart 1598:     	        $file_counter++;
                   1599: 	    }
1.322     albertel 1600: 	}
1.313     banghart 1601:     }
1.318     banghart 1602:     return $result;    
1.71      ng       1603: }
1.44      ng       1604: 
1.58      albertel 1605: sub show_problem {
1.382     albertel 1606:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1607:     my $rendered;
1.382     albertel 1608:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1609:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1610:     if ($mode eq 'both' or $mode eq 'text') {
                   1611: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1612: 						       $env{'request.course.id'},
                   1613: 						       undef,\%form);
1.144     albertel 1614:     }
1.58      albertel 1615:     if ($removeform) {
                   1616: 	$rendered=~s|<form(.*?)>||g;
                   1617: 	$rendered=~s|</form>||g;
1.374     albertel 1618: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1619:     }
1.144     albertel 1620:     my $companswer;
                   1621:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1622: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1623: 	$companswer=
                   1624: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1625: 						    $env{'request.course.id'},
                   1626: 						    %form);
1.144     albertel 1627:     }
1.58      albertel 1628:     if ($removeform) {
                   1629: 	$companswer=~s|<form(.*?)>||g;
                   1630: 	$companswer=~s|</form>||g;
1.144     albertel 1631: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1632:     }
                   1633:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1634:     $result.='<table border="0" width="100%">';
1.144     albertel 1635:     if ($viewon) {
                   1636: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1637: 	if ($mode eq 'both' or $mode eq 'text') {
                   1638: 	    $result.='View of the problem - ';
                   1639: 	} else {
                   1640: 	    $result.='Correct answer: ';
                   1641: 	}
1.257     albertel 1642: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1643:     }
                   1644:     if ($mode eq 'both') {
                   1645: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1646: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1647:     } elsif ($mode eq 'text') {
                   1648: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1649:     } elsif ($mode eq 'answer') {
                   1650: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1651:     }
1.58      albertel 1652:     $result.='</td></tr></table>';
                   1653:     $result.='</td></tr></table><br />';
1.71      ng       1654:     return $result;
1.58      albertel 1655: }
1.397     albertel 1656: 
1.396     banghart 1657: sub files_exist {
                   1658:     my ($r, $symb) = @_;
                   1659:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1660: 
1.396     banghart 1661:     foreach my $student (@students) {
                   1662:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1663:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1664: 					      $udom,$uname);
1.396     banghart 1665:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1666:         foreach my $submission (@$string) {
                   1667:             my ($partid,$respid) =
                   1668: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1669:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1670: 					   \%record);
                   1671:             return 1 if (@$files);
1.396     banghart 1672:         }
                   1673:     }
1.397     albertel 1674:     return 0;
1.396     banghart 1675: }
1.397     albertel 1676: 
1.394     banghart 1677: sub download_all_link {
                   1678:     my ($r,$symb) = @_;
1.395     albertel 1679:     my $all_students = 
                   1680: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1681: 
                   1682:     my $parts =
                   1683: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1684: 
1.394     banghart 1685:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1686:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1687:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1688:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1689:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1690: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1691:     return
                   1692: }
1.395     albertel 1693: 
1.432     banghart 1694: sub build_section_inputs {
                   1695:     my $section_inputs;
                   1696:     if ($env{'form.section'} eq '') {
                   1697:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1698:     } else {
                   1699:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434   ! albertel 1700:         foreach my $section (@sections) {
1.432     banghart 1701:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1702:         }
                   1703:     }
                   1704:     return $section_inputs;
                   1705: }
                   1706: 
1.44      ng       1707: # --------------------------- show submissions of a student, option to grade 
                   1708: sub submission {
                   1709:     my ($request,$counter,$total) = @_;
                   1710: 
1.257     albertel 1711:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1712:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1713:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1714:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.41      ng       1715: 
1.324     albertel 1716:     my $symb = &get_symb($request); 
                   1717:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1718: 
                   1719:     if (!&canview($usec)) {
1.398     albertel 1720: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1721: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1722: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1723: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1724: 	return;
                   1725:     }
                   1726: 
1.257     albertel 1727:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1728:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1729:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1730:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1731:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1732: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1733: 	'/check.gif" height="16" border="0" />';
1.41      ng       1734: 
1.426     albertel 1735:     my %old_essays;
1.41      ng       1736:     # header info
                   1737:     if ($counter == 0) {
                   1738: 	&sub_page_js($request);
1.257     albertel 1739: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1740: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1741: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1742: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1743: 	    &download_all_link($request, $symb);
                   1744: 	}
1.398     albertel 1745: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
                   1746: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1.118     ng       1747: 
1.257     albertel 1748: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1749: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1750: 		$checkIcon.' symbol.'."\n";
                   1751: 	    $request->print($checkMark);
                   1752: 	}
1.41      ng       1753: 
1.44      ng       1754: 	# option to display problem, only once else it cause problems 
                   1755:         # with the form later since the problem has a form.
1.257     albertel 1756: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1757: 	    my $mode;
1.257     albertel 1758: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1759: 		$mode='both';
1.257     albertel 1760: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1761: 		$mode='text';
1.257     albertel 1762: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1763: 		$mode='answer';
                   1764: 	    }
1.329     albertel 1765: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1766: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1767: 	}
                   1768: 	
1.44      ng       1769: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1770:         # if this subroutine has been called once.
1.41      ng       1771: 	my %keyhash = ();
1.257     albertel 1772: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1773: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1774: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1775: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1776: 
1.257     albertel 1777: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1778: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1779: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1780: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1781: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1782: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1783: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1784: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1785: 	}
1.257     albertel 1786: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.303     banghart 1787: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1788: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1789: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
                   1790: 			'<input type="hidden" name="Status"     value="'.$env{'form.Status'}.'" />'."\n".
1.120     ng       1791: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1792: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1793: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1794: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1795: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1796: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1797: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1798: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1799: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1800: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1801: 			&build_section_inputs().
1.326     albertel 1802: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1803: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1804: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1805: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1806: 	if ($env{'form.handgrade'} eq 'yes') {
                   1807: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1808: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1809: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1810: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1811: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1812: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1813: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1814: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1815: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1816: 	    }
1.123     ng       1817: 	}
1.41      ng       1818: 	
                   1819: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1820: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1821: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1822: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1823: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1824: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1825: 		'" />'."\n".
                   1826: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1827: 	    $cts++;
                   1828: 	}
                   1829: 	$request->print($prnmsg);
1.32      ng       1830: 
1.257     albertel 1831: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1832: #
                   1833: # Print out the keyword options line
                   1834: #
1.41      ng       1835: 	    $request->print(<<KEYWORDS);
1.38      ng       1836: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1837: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1838: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1839:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1840: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1841: KEYWORDS
1.88      www      1842: #
                   1843: # Load the other essays for similarity check
                   1844: #
1.324     albertel 1845:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1846: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1847: 	    $apath=&escape($apath);
1.88      www      1848: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1849: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1850:         }
                   1851:     }
1.44      ng       1852: 
1.257     albertel 1853:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.71      ng       1854: 	$request->print('<br /><br /><br />') if ($counter > 0);
1.144     albertel 1855: 	my $mode;
1.257     albertel 1856: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1857: 	    $mode='both';
1.257     albertel 1858: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1859: 	    $mode='text';
1.257     albertel 1860: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1861: 	    $mode='answer';
                   1862: 	}
1.329     albertel 1863: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1864: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1865:     }
1.144     albertel 1866: 
1.257     albertel 1867:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1868:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1869: 
1.44      ng       1870:     # Display student info
1.41      ng       1871:     $request->print(($counter == 0 ? '' : '<br />'));
1.326     albertel 1872:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
                   1873: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1.44      ng       1874: 
1.257     albertel 1875:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1.45      ng       1876:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1877: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1878: 
1.118     ng       1879:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.45      ng       1880:     my @col_fullnames;
1.56      matthew  1881:     my ($classlist,$fullname);
1.257     albertel 1882:     if ($env{'form.handgrade'} eq 'yes') {
1.80      ng       1883: 	($classlist,undef,$fullname) = &getclasslist('all','0');
1.41      ng       1884: 	for (keys (%$handgrade)) {
1.44      ng       1885: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1.57      matthew  1886: 					    '.maxcollaborators',
                   1887:                                             $symb,$udom,$uname);
                   1888: 	    next if ($ncol <= 0);
                   1889:             s/\_/\./g;
                   1890:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
1.86      ng       1891:             my @goodcollaborators = ();
                   1892:             my @badcollaborators  = ();
                   1893: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
                   1894: 		$_ =~ s/[\$\^\(\)]//g;
                   1895: 		next if ($_ eq '');
1.80      ng       1896: 		my ($co_name,$co_dom) = split /\@|:/,$_;
1.86      ng       1897: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1.80      ng       1898: 		next if ($co_name eq $uname && $co_dom eq $udom);
1.86      ng       1899: 		# Doing this grep allows 'fuzzy' specification
                   1900: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
                   1901: 		if (! scalar(@Matches)) {
                   1902: 		    push @badcollaborators,$_;
                   1903: 		} else {
                   1904: 		    push @goodcollaborators, @Matches;
                   1905: 		}
1.80      ng       1906: 	    }
1.86      ng       1907:             if (scalar(@goodcollaborators) != 0) {
1.57      matthew  1908:                 $result.='<b>Collaborators: </b>';
1.86      ng       1909:                 foreach (@goodcollaborators) {
                   1910: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
                   1911: 		    push @col_fullnames, $givenn.' '.$lastname;
                   1912: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
                   1913: 		}
1.57      matthew  1914:                 $result.='<br />'."\n";
1.150     albertel 1915: 		my ($part)=split(/\./,$_);
1.86      ng       1916: 		$result.='<input type="hidden" name="collaborator'.$counter.
1.150     albertel 1917: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
                   1918: 		    "\n";
1.86      ng       1919: 	    }
                   1920: 	    if (scalar(@badcollaborators) > 0) {
                   1921: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1922: 		$result.='This student has submitted ';
                   1923: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
                   1924: 		$result .= ': '.join(', ',@badcollaborators);
                   1925: 		$result .= '</td></tr></table>';
                   1926: 	    }         
                   1927: 	    if (scalar(@badcollaborators > $ncol)) {
                   1928: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1929: 		$result .= 'This student has submitted too many '.
                   1930: 		    'collaborators.  Maximum is '.$ncol.'.';
                   1931: 		$result .= '</td></tr></table>';
                   1932: 	    }
1.41      ng       1933: 	}
                   1934:     }
1.44      ng       1935:     $request->print($result."\n");
1.33      ng       1936: 
1.44      ng       1937:     # print student answer/submission
                   1938:     # Options are (1) Handgaded submission only
                   1939:     #             (2) Last submission, includes submission that is not handgraded 
                   1940:     #                  (for multi-response type part)
                   1941:     #             (3) Last submission plus the parts info
                   1942:     #             (4) The whole record for this student
1.257     albertel 1943:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 1944: 	my ($string,$timestamp)= &get_last_submission(\%record);
                   1945: 	my $lastsubonly=''.
                   1946: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
                   1947: 	     $$timestamp)."</td></tr>\n";
                   1948: 	if ($$timestamp eq '') {
                   1949: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
                   1950: 	} else {
                   1951: 	    my %seenparts;
1.375     albertel 1952: 	    my @part_response_id = &flatten_responseType($responseType);
                   1953: 	    foreach my $part (@part_response_id) {
1.393     albertel 1954: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   1955: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   1956: 
1.375     albertel 1957: 		my ($partid,$respid) = @{ $part };
1.324     albertel 1958: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 1959: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 1960: 		    if (exists($seenparts{$partid})) { next; }
                   1961: 		    $seenparts{$partid}=1;
1.207     albertel 1962: 		    my $submitby='<b>Part:</b> '.$display_part.
                   1963: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 1964: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 1965: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 1966: 			'\');" target="_self">'.
1.257     albertel 1967: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 1968: 		    $request->print($submitby);
                   1969: 		    next;
                   1970: 		}
                   1971: 		my $responsetype = $responseType->{$partid}->{$respid};
                   1972: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.207     albertel 1973: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1.398     albertel 1974: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   1975: 			' )</span>&nbsp; &nbsp;'.
                   1976: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1.151     albertel 1977: 		    next;
                   1978: 		}
                   1979: 		foreach (@$string) {
                   1980: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1.375     albertel 1981: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.151     albertel 1982: 		    my ($ressub,$subval) = split(/:/,$_,2);
                   1983: 		    # Similarity check
                   1984: 		    my $similar='';
1.257     albertel 1985: 		    if($env{'form.checkPlag'}){
1.151     albertel 1986: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 1987: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 1988: 			if ($osim) {
                   1989: 			    $osim=int($osim*100.0);
1.426     albertel 1990: 			    my %old_course_desc = 
                   1991: 				&Apache::lonnet::coursedescription($ocrsid,
                   1992: 								   {'one_time' => 1});
                   1993: 
                   1994: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 1995: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 1996: 				    $osim,
                   1997: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 1998: 				    $oname,$odom,
1.426     albertel 1999: 				    $old_course_desc{'description'},
1.427     albertel 2000: 				    $old_course_desc{'num'},
1.426     albertel 2001: 				    $old_course_desc{'domain'}).
1.398     albertel 2002: 				'</span></h3><blockquote><i>'.
1.151     albertel 2003: 				&keywords_highlight($oessay).
                   2004: 				'</i></blockquote><hr />';
                   2005: 			}
1.150     albertel 2006: 		    }
1.151     albertel 2007: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2008: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2009: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2010: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2011: 			my $display_part=&get_display_part($partid,$symb);
1.403     albertel 2012: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   2013: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2014: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2015: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2016: 			if (@$files) {
1.398     albertel 2017: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1.303     banghart 2018: 			    my $file_counter = 0;
1.313     banghart 2019: 			    foreach my $file (@$files) {
1.303     banghart 2020: 			        $file_counter ++;
1.232     albertel 2021: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2022: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2023: 			    }
1.236     albertel 2024: 			    $lastsubonly.='<br />';
1.41      ng       2025: 			}
1.151     albertel 2026: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   2027: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2028: 					 $respid,\%record,$order);
                   2029: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       2030: 		    }
                   2031: 		}
                   2032: 	    }
1.151     albertel 2033: 	}
                   2034: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   2035: 	$request->print($lastsubonly);
1.257     albertel 2036:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2037: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2038: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2039:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2040: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2041: 								 $env{'request.course.id'},
1.44      ng       2042: 								 $last,'.submission',
                   2043: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2044:     }
1.120     ng       2045: 
1.121     ng       2046:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2047: 	.$udom.'" />'."\n");
1.41      ng       2048:     
1.44      ng       2049:     # return if view submission with no grading option
1.257     albertel 2050:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2051: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2052: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2053: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 2054: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 2055: 	if (($env{'form.command'} eq 'submission') || 
                   2056: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2057: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2058: 	}
1.180     albertel 2059: 	$request->print($toGrade);
1.41      ng       2060: 	return;
1.180     albertel 2061:     } else {
                   2062: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       2063:     }
1.33      ng       2064: 
1.121     ng       2065:     # essay grading message center
1.257     albertel 2066:     if ($env{'form.handgrade'} eq 'yes') {
                   2067: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2068: 	my $msgfor = $givenn.' '.$lastname;
                   2069: 	if (scalar(@col_fullnames) > 0) {
                   2070: 	    my $lastone = pop @col_fullnames;
                   2071: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   2072: 	}
                   2073: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       2074: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2075: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2076: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2077: 	    ',\''.$msgfor.'\');" target="_self">'.
1.350     albertel 2078: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
                   2079: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2080: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2081: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2082: 	    '<br />&nbsp;('.
                   2083: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       2084: 	$request->print($result);
1.118     ng       2085:     }
1.300     albertel 2086:     if ($perm{'vgr'}) {
1.297     www      2087: 	$request->print('<br />'.
1.300     albertel 2088: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2089: 						   $uname,$udom,'check'));
1.297     www      2090:     }
1.300     albertel 2091:     if ($perm{'opa'}) {
1.297     www      2092: 	$request->print('<br />'.
1.300     albertel 2093: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2094: 					 $uname,$udom,$symb,'check'));
1.297     www      2095:     }
1.41      ng       2096: 
                   2097:     my %seen = ();
                   2098:     my @partlist;
1.129     ng       2099:     my @gradePartRespid;
1.375     albertel 2100:     my @part_response_id = &flatten_responseType($responseType);
                   2101:     foreach my $part_response_id (@part_response_id) {
                   2102:     	my ($partid,$respid) = @{ $part_response_id };
                   2103: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2104: 	next if ($seen{$partid} > 0);
1.41      ng       2105: 	$seen{$partid}++;
1.393     albertel 2106: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2107: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2108: 	push @partlist,$partid;
1.129     ng       2109: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2110: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2111:     }
1.45      ng       2112:     $result='<input type="hidden" name="partlist'.$counter.
                   2113: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2114:     $result.='<input type="hidden" name="gradePartRespid'.
                   2115: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2116:     my $ctr = 0;
                   2117:     while ($ctr < scalar(@partlist)) {
                   2118: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2119: 	    $partlist[$ctr].'" />'."\n";
                   2120: 	$ctr++;
                   2121:     }
                   2122:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       2123: 
                   2124:     # print end of form
                   2125:     if ($counter == $total) {
1.297     www      2126: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2127: 	$endform.='<input type="button" value="Save & Next" '.
                   2128: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2129: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2130: 	my $ntstu ='<select name="NTSTU">'.
                   2131: 	    '<option>1</option><option>2</option>'.
                   2132: 	    '<option>3</option><option>5</option>'.
                   2133: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2134: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2135: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.119     ng       2136: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2137: 	$endform.='<input type="button" value="Previous" '.
1.417     albertel 2138: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.126     ng       2139: 	    '<input type="button" value="Next" '.
1.417     albertel 2140: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.126     ng       2141: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2142:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2143:             "' name='increment' />";
1.45      ng       2144: 	$endform.='</td><tr></table></form>';
1.324     albertel 2145: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2146: 	$request->print($endform);
                   2147:     }
                   2148:     return '';
1.38      ng       2149: }
                   2150: 
1.44      ng       2151: #--- Retrieve the last submission for all the parts
1.38      ng       2152: sub get_last_submission {
1.119     ng       2153:     my ($returnhash)=@_;
1.46      ng       2154:     my (@string,$timestamp);
1.119     ng       2155:     if ($$returnhash{'version'}) {
1.46      ng       2156: 	my %lasthash=();
                   2157: 	my ($version);
1.119     ng       2158: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2159: 	    foreach my $key (sort(split(/\:/,
                   2160: 					$$returnhash{$version.':keys'}))) {
                   2161: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2162: 		$timestamp = 
                   2163: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2164: 	    }
                   2165: 	}
1.397     albertel 2166: 	foreach my $key (keys(%lasthash)) {
                   2167: 	    next if ($key !~ /\.submission$/);
                   2168: 
                   2169: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2170: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2171: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2172: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2173: 	}
                   2174:     }
1.397     albertel 2175:     if (!@string) {
                   2176: 	$string[0] =
1.398     albertel 2177: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2178:     }
                   2179:     return (\@string,\$timestamp);
1.38      ng       2180: }
1.35      ng       2181: 
1.44      ng       2182: #--- High light keywords, with style choosen by user.
1.38      ng       2183: sub keywords_highlight {
1.44      ng       2184:     my $string    = shift;
1.257     albertel 2185:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2186:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2187:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2188:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2189:     foreach my $keyword (@keylist) {
                   2190: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2191:     }
                   2192:     return $string;
1.38      ng       2193: }
1.36      ng       2194: 
1.44      ng       2195: #--- Called from submission routine
1.38      ng       2196: sub processHandGrade {
1.41      ng       2197:     my ($request) = shift;
1.324     albertel 2198:     my $symb   = &get_symb($request);
                   2199:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2200:     my $button = $env{'form.gradeOpt'};
                   2201:     my $ngrade = $env{'form.NCT'};
                   2202:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2203:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2204:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2205: 
1.44      ng       2206:     if ($button eq 'Save & Next') {
                   2207: 	my $ctr = 0;
                   2208: 	while ($ctr < $ngrade) {
1.257     albertel 2209: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2210: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2211: 	    if ($errorflag eq 'no_score') {
                   2212: 		$ctr++;
                   2213: 		next;
                   2214: 	    }
1.104     albertel 2215: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2216: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2217: 		$ctr++;
                   2218: 		next;
                   2219: 	    }
1.257     albertel 2220: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2221: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2222: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2223:             my ($feedurl,$showsymb) =
                   2224: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2225: 	    my $messagetail;
1.62      albertel 2226: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2227: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2228: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2229: 		$subject.=' ['.$restitle.']';
1.44      ng       2230: 		my (@msgnum) = split(/,/,$includemsg);
                   2231: 		foreach (@msgnum) {
1.257     albertel 2232: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2233: 		}
1.80      ng       2234: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2235: 		if ($env{'form.withgrades'.$ctr}) {
                   2236: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2237: 		    $messagetail = " for <a href=\"".
1.418     albertel 2238: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2239: 		}
                   2240: 		$msgstatus = 
                   2241:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2242: 						     $message.$messagetail,
1.418     albertel 2243:                                                      undef,$feedurl,undef,
1.386     raeburn  2244:                                                      undef,undef,$showsymb,
                   2245:                                                      $restitle);
                   2246: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2247: 				$msgstatus);
1.44      ng       2248: 	    }
1.257     albertel 2249: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2250: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2251: 		foreach my $collabstr (@collabstrs) {
                   2252: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2253: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2254: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2255: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2256: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2257: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2258: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2259: 			    next;
1.418     albertel 2260: 			} elsif ($message ne '') {
                   2261: 			    my ($baseurl,$showsymb) = 
                   2262: 				&get_feedurl_and_symb($symb,$collaborator,
                   2263: 						      $udom);
                   2264: 			    if ($env{'form.withgrades'.$ctr}) {
                   2265: 				$messagetail = " for <a href=\"".
1.386     raeburn  2266:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2267: 			    }
1.418     albertel 2268: 			    $msgstatus = 
                   2269: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2270: 			}
1.44      ng       2271: 		    }
                   2272: 		}
                   2273: 	    }
                   2274: 	    $ctr++;
                   2275: 	}
                   2276:     }
                   2277: 
1.257     albertel 2278:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2279: 	# Keywords sorted in alphabatical order
1.257     albertel 2280: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2281: 	my %keyhash = ();
1.257     albertel 2282: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2283: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2284: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2285: 	$env{'form.keywords'} = join(' ',@keywords);
                   2286: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2287: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2288: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2289: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2290: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2291: 
                   2292: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2293: 	# New messages are saved in env for the next student.
1.119     ng       2294: 	# All messages are saved in nohist_handgrade.db
                   2295: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2296: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2297: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2298: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2299: 		$idx++;
                   2300: 	    }
                   2301: 	    $ctr++;
1.41      ng       2302: 	}
1.119     ng       2303: 	$ctr = 0;
                   2304: 	while ($ctr < $ngrade) {
1.257     albertel 2305: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2306: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2307: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2308: 		$idx++;
                   2309: 	    }
                   2310: 	    $ctr++;
1.41      ng       2311: 	}
1.257     albertel 2312: 	$env{'form.savemsgN'} = --$idx;
                   2313: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2314: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2315: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2316:     }
1.44      ng       2317:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2318:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2319:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2320: 	my ($ctr,$total) = (0,0);
                   2321: 	while ($ctr < $ngrade) {
1.257     albertel 2322: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2323: 	    $ctr++;
                   2324: 	}
1.257     albertel 2325: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2326: 	$ctr = 0;
                   2327: 	while ($ctr < $total) {
1.257     albertel 2328: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2329: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2330: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2331: 	    &submission($request,$ctr,$total-1);
1.41      ng       2332: 	    $ctr++;
                   2333: 	}
                   2334: 	return '';
                   2335:     }
1.36      ng       2336: 
1.121     ng       2337: # Go directly to grade student - from submission or link from chart page
1.120     ng       2338:     if ($button eq 'Grade Student') {
1.324     albertel 2339: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2340: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2341: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2342: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2343: 	&submission($request,0,0);
                   2344: 	return '';
                   2345:     }
                   2346: 
1.44      ng       2347:     # Get the next/previous one or group of students
1.257     albertel 2348:     my $firststu = $env{'form.unamedom0'};
                   2349:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2350:     my $ctr = 2;
1.41      ng       2351:     while ($laststu eq '') {
1.257     albertel 2352: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2353: 	$ctr++;
                   2354: 	$laststu = $firststu if ($ctr > $ngrade);
                   2355:     }
1.44      ng       2356: 
1.41      ng       2357:     my (@parsedlist,@nextlist);
                   2358:     my ($nextflg) = 0;
1.294     albertel 2359:     foreach (sort 
                   2360: 	     {
                   2361: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2362: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2363: 		 }
                   2364: 		 return $a cmp $b;
                   2365: 	     } (keys(%$fullname))) {
1.41      ng       2366: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2367: 	    push @parsedlist,$_;
                   2368: 	}
                   2369: 	$nextflg = 1 if ($_ eq $laststu);
                   2370: 	if ($button eq 'Previous') {
                   2371: 	    last if ($_ eq $firststu);
                   2372: 	    push @parsedlist,$_;
                   2373: 	}
                   2374:     }
                   2375:     $ctr = 0;
                   2376:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2377:     my ($partlist) = &response_type($symb);
1.41      ng       2378:     foreach my $student (@parsedlist) {
1.257     albertel 2379: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2380: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2381: 	
                   2382: 	if ($submitonly eq 'queued') {
                   2383: 	    my %queue_status = 
                   2384: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2385: 							$udom,$uname);
                   2386: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2387: 	}
                   2388: 
1.156     albertel 2389: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2390: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2391: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2392: 	    my $submitted = 0;
1.248     albertel 2393: 	    my $ungraded = 0;
                   2394: 	    my $incorrect = 0;
1.145     albertel 2395: 	    foreach (keys(%status)) {
                   2396: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2397: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2398: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2399: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2400: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2401: 		    $submitted = 0;
                   2402: 		}
1.41      ng       2403: 	    }
1.156     albertel 2404: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2405: 				     $submitonly eq 'incorrect' ||
                   2406: 				     $submitonly eq 'graded'));
1.248     albertel 2407: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2408: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2409: 	}
                   2410: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2411: 	last if ($ctr == $ntstu);
1.41      ng       2412: 	$ctr++;
                   2413:     }
1.36      ng       2414: 
1.41      ng       2415:     $ctr = 0;
                   2416:     my $total = scalar(@nextlist)-1;
1.39      ng       2417: 
1.41      ng       2418:     foreach (sort @nextlist) {
                   2419: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2420: 	$env{'form.student'}  = $uname;
                   2421: 	$env{'form.userdom'}  = $udom;
                   2422: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2423: 	&submission($request,$ctr,$total);
                   2424: 	$ctr++;
                   2425:     }
                   2426:     if ($total < 0) {
1.398     albertel 2427: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
1.41      ng       2428: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2429: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2430: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2431: 	$request->print($the_end);
                   2432:     }
                   2433:     return '';
1.38      ng       2434: }
1.36      ng       2435: 
1.44      ng       2436: #---- Save the score and award for each student, if changed
1.38      ng       2437: sub saveHandGrade {
1.324     albertel 2438:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2439:     my @version_parts;
1.104     albertel 2440:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2441: 					   $env{'request.course.id'});
1.104     albertel 2442:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2443:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2444:     my @parts_graded;
1.77      ng       2445:     my %newrecord  = ();
                   2446:     my ($pts,$wgt) = ('','');
1.269     raeburn  2447:     my %aggregate = ();
                   2448:     my $aggregateflag = 0;
1.301     albertel 2449:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2450:     foreach my $new_part (@parts) {
1.337     banghart 2451: 	#collaborator ($submi may vary for different parts
1.259     banghart 2452: 	if ($submitter && $new_part ne $part) { next; }
                   2453: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2454: 	if ($dropMenu eq 'excused') {
1.259     banghart 2455: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2456: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2457: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2458: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2459: 		}
1.364     banghart 2460: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2461: 	    }
1.125     ng       2462: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2463: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2464: 	    foreach my $key (keys (%record)) {
1.259     banghart 2465: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2466: 	    }
1.259     banghart 2467: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2468: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2469:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2470: 
                   2471:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2472: 					       [$new_part]);
                   2473:             my $aggtries =$totaltries;
1.269     raeburn  2474:             if ($last_resets{$new_part}) {
1.270     albertel 2475:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2476: 					   $new_part);
1.269     raeburn  2477:             }
1.270     albertel 2478: 
                   2479:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2480:             if ($aggtries > 0) {
1.327     albertel 2481:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2482:                 $aggregateflag = 1;
                   2483:             }
1.125     ng       2484: 	} elsif ($dropMenu eq '') {
1.259     banghart 2485: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2486: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2487: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2488: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2489: 		next;
                   2490: 	    }
1.259     banghart 2491: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2492: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2493: 	    my $partial= $pts/$wgt;
1.259     banghart 2494: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2495: 		#do not update score for part if not changed.
1.346     banghart 2496:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2497: 		next;
1.251     banghart 2498: 	    } else {
1.259     banghart 2499: 	        push @parts_graded, $new_part;
1.153     albertel 2500: 	    }
1.259     banghart 2501: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2502: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2503: 	    }
1.259     banghart 2504: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2505: 	    if ($partial == 0) {
1.153     albertel 2506: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2507: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2508: 		}
1.41      ng       2509: 	    } else {
1.153     albertel 2510: 		if ($record{$reckey} ne 'correct_by_override') {
                   2511: 		    $newrecord{$reckey} = 'correct_by_override';
                   2512: 		}
                   2513: 	    }	    
                   2514: 	    if ($submitter && 
1.259     banghart 2515: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2516: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2517: 	    }
1.259     banghart 2518: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2519: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2520: 	}
1.259     banghart 2521: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2522: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2523: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2524: 	        $dropMenu eq 'reset status')
                   2525: 	   {
1.342     banghart 2526: 	    push (@version_parts,$new_part);
1.259     banghart 2527: 	}
1.41      ng       2528:     }
1.301     albertel 2529:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2530:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2531: 
1.344     albertel 2532:     if (%newrecord) {
                   2533:         if (@version_parts) {
1.364     banghart 2534:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2535:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2536: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2537: 	    foreach my $new_part (@version_parts) {
                   2538: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2539: 				$new_part,\%newrecord);
                   2540: 	    }
1.259     banghart 2541:         }
1.44      ng       2542: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2543: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2544: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2545: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2546:     }
1.269     raeburn  2547:     if ($aggregateflag) {
                   2548:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2549: 			      $cdom,$cnum);
1.269     raeburn  2550:     }
1.301     albertel 2551:     return ('',$pts,$wgt);
1.36      ng       2552: }
1.322     albertel 2553: 
1.380     albertel 2554: sub check_and_remove_from_queue {
                   2555:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2556:     my @ungraded_parts;
                   2557:     foreach my $part (@{$parts}) {
                   2558: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2559: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2560: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2561: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2562: 		) {
                   2563: 	    push(@ungraded_parts, $part);
                   2564: 	}
                   2565:     }
                   2566:     if ( !@ungraded_parts ) {
                   2567: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2568: 					       $cnum,$domain,$stuname);
                   2569:     }
                   2570: }
                   2571: 
1.337     banghart 2572: sub handback_files {
                   2573:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2574:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2575:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2576: 
                   2577:     my @part_response_id = &flatten_responseType($responseType);
                   2578:     foreach my $part_response_id (@part_response_id) {
                   2579:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2580: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2581:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2582:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2583:                 my $file_counter = 1;
1.367     albertel 2584: 		my $file_msg;
1.337     banghart 2585:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2586:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2587:                     my ($directory,$answer_file) = 
                   2588:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2589:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2590: 		        &file_name_version_ext($answer_file);
1.355     banghart 2591: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2592: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2593: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2594:                     # fix file name
                   2595:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2596:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2597:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2598:             	                                $save_file_name);
1.337     banghart 2599:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2600:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2601:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2602:                     } else {
1.360     banghart 2603:                         # mark the file as read only
                   2604:                         my @files = ($save_file_name);
1.372     albertel 2605:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2606:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2607: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2608: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2609: 			}
                   2610:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2611: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2612: 
1.337     banghart 2613:                     }
                   2614:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2615:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2616:                     $file_counter++;
                   2617:                 }
1.367     albertel 2618: 		my $subject = "File Handed Back by Instructor ";
                   2619: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2620: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2621: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2622: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2623: 		my ($feedurl,$showsymb) = 
                   2624: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2625:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2626: 		my $msgstatus = 
                   2627:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2628: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2629:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2630:             }
                   2631:         }
1.338     banghart 2632:     return;
1.337     banghart 2633: }
                   2634: 
1.418     albertel 2635: sub get_feedurl_and_symb {
                   2636:     my ($symb,$uname,$udom) = @_;
                   2637:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2638:     $url = &Apache::lonnet::clutter($url);
                   2639:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2640: 					$symb,$udom,$uname);
                   2641:     if ($encrypturl =~ /^yes$/i) {
                   2642: 	&Apache::lonenc::encrypted(\$url,1);
                   2643: 	&Apache::lonenc::encrypted(\$symb,1);
                   2644:     }
                   2645:     return ($url,$symb);
                   2646: }
                   2647: 
1.313     banghart 2648: sub get_submitted_files {
                   2649:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2650:     my @files;
                   2651:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2652:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2653:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2654:     	    push(@files,$file_url.$file);
                   2655:         }
                   2656:     }
                   2657:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2658:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2659:     }
                   2660:     return (\@files);
                   2661: }
1.322     albertel 2662: 
1.269     raeburn  2663: # ----------- Provides number of tries since last reset.
                   2664: sub get_num_tries {
                   2665:     my ($record,$last_reset,$part) = @_;
                   2666:     my $timestamp = '';
                   2667:     my $num_tries = 0;
                   2668:     if ($$record{'version'}) {
                   2669:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2670:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2671:                 $timestamp = $$record{$version.':timestamp'};
                   2672:                 if ($timestamp > $last_reset) {
                   2673:                     $num_tries ++;
                   2674:                 } else {
                   2675:                     last;
                   2676:                 }
                   2677:             }
                   2678:         }
                   2679:     }
                   2680:     return $num_tries;
                   2681: }
                   2682: 
                   2683: # ----------- Determine decrements required in aggregate totals 
                   2684: sub decrement_aggs {
                   2685:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2686:     my %decrement = (
                   2687:                         attempts => 0,
                   2688:                         users => 0,
                   2689:                         correct => 0
                   2690:                     );
                   2691:     $decrement{'attempts'} = $aggtries;
                   2692:     if ($solvedstatus =~ /^correct/) {
                   2693:         $decrement{'correct'} = 1;
                   2694:     }
                   2695:     if ($aggtries == $totaltries) {
                   2696:         $decrement{'users'} = 1;
                   2697:     }
                   2698:     foreach my $type (keys (%decrement)) {
                   2699:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2700:     }
                   2701:     return;
                   2702: }
                   2703: 
                   2704: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2705: sub get_last_resets {
1.270     albertel 2706:     my ($symb,$courseid,$partids) =@_;
                   2707:     my %last_resets;
1.269     raeburn  2708:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2709:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2710:     my @keys;
                   2711:     foreach my $part (@{$partids}) {
                   2712: 	push(@keys,"$symb\0$part\0resettime");
                   2713:     }
                   2714:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2715: 				     $cdom,$cname);
                   2716:     foreach my $part (@{$partids}) {
                   2717: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2718:     }
1.270     albertel 2719:     return %last_resets;
1.269     raeburn  2720: }
                   2721: 
1.251     banghart 2722: # ----------- Handles creating versions for portfolio files as answers
                   2723: sub version_portfiles {
1.343     banghart 2724:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2725:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2726:     my @returned_keys;
1.255     banghart 2727:     my $parts = join('|', @$parts_graded);
1.359     www      2728:     my $portfolio_root = &propath($domain,$stu_name).
                   2729: 	'/userfiles/portfolio';
1.277     albertel 2730:     foreach my $key (keys(%$record)) {
1.259     banghart 2731:         my $new_portfiles;
1.263     banghart 2732:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2733:             my @versioned_portfiles;
1.367     albertel 2734:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2735:             foreach my $file (@portfiles) {
1.306     banghart 2736:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2737:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2738: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2739: 		    &file_name_version_ext($answer_file);
1.306     banghart 2740:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2741:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2742:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2743:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2744:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2745:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2746:                         [$directory.$new_answer],
1.306     banghart 2747:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2748:                 }
1.252     banghart 2749:             }
1.343     banghart 2750:             $$record{$key} = join(',',@versioned_portfiles);
                   2751:             push(@returned_keys,$key);
1.251     banghart 2752:         }
                   2753:     } 
1.343     banghart 2754:     return (@returned_keys);   
1.305     banghart 2755: }
                   2756: 
1.307     banghart 2757: sub get_next_version {
1.341     banghart 2758:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2759:     my $version;
                   2760:     foreach my $row (@$dir_list) {
                   2761:         my ($file) = split(/\&/,$row,2);
                   2762:         my ($file_name,$file_version,$file_ext) =
                   2763: 	    &file_name_version_ext($file);
                   2764:         if (($file_name eq $answer_name) && 
                   2765: 	    ($file_ext eq $answer_ext)) {
                   2766:                 # gets here if filename and extension match, regardless of version
                   2767:                 if ($file_version ne '') {
                   2768:                 # a versioned file is found  so save it for later
                   2769:                 if ($file_version > $version) {
                   2770: 		    $version = $file_version;
                   2771: 	        }
                   2772:             }
                   2773:         }
                   2774:     } 
                   2775:     $version ++;
                   2776:     return($version);
                   2777: }
                   2778: 
1.305     banghart 2779: sub version_selected_portfile {
1.306     banghart 2780:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2781:     my ($answer_name,$answer_ver,$answer_ext) =
                   2782:         &file_name_version_ext($file_name);
                   2783:     my $new_answer;
                   2784:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2785:     if($env{'form.copy'} eq '-1') {
                   2786:         &Apache::lonnet::logthis('problem getting file '.$file_name);
                   2787:         $new_answer = 'problem getting file';
                   2788:     } else {
                   2789:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2790:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2791:                             $stu_name,$domain,'copy',
                   2792: 		        '/portfolio'.$directory.$new_answer);
                   2793:     }    
                   2794:     return ($new_answer);
1.251     banghart 2795: }
                   2796: 
1.304     albertel 2797: sub file_name_version_ext {
                   2798:     my ($file)=@_;
                   2799:     my @file_parts = split(/\./, $file);
                   2800:     my ($name,$version,$ext);
                   2801:     if (@file_parts > 1) {
                   2802: 	$ext=pop(@file_parts);
                   2803: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2804: 	    $version=pop(@file_parts);
                   2805: 	}
                   2806: 	$name=join('.',@file_parts);
                   2807:     } else {
                   2808: 	$name=join('.',@file_parts);
                   2809:     }
                   2810:     return($name,$version,$ext);
                   2811: }
                   2812: 
1.44      ng       2813: #--------------------------------------------------------------------------------------
                   2814: #
                   2815: #-------------------------- Next few routines handles grading by section or whole class
                   2816: #
                   2817: #--- Javascript to handle grading by section or whole class
1.42      ng       2818: sub viewgrades_js {
                   2819:     my ($request) = shift;
                   2820: 
1.41      ng       2821:     $request->print(<<VIEWJAVASCRIPT);
                   2822: <script type="text/javascript" language="javascript">
1.45      ng       2823:    function writePoint(partid,weight,point) {
1.125     ng       2824: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2825: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2826: 	if (point == "textval") {
1.125     ng       2827: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2828: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2829: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2830: 		var resetbox = false;
                   2831: 		for (var i=0; i<radioButton.length; i++) {
                   2832: 		    if (radioButton[i].checked) {
                   2833: 			textbox.value = i;
                   2834: 			resetbox = true;
                   2835: 		    }
                   2836: 		}
                   2837: 		if (!resetbox) {
                   2838: 		    textbox.value = "";
                   2839: 		}
                   2840: 		return;
                   2841: 	    }
1.109     matthew  2842: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2843: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2844: 				   ") greater than the weight for the part. Accept?");
                   2845: 		if (resp == false) {
                   2846: 		    textbox.value = "";
                   2847: 		    return;
                   2848: 		}
                   2849: 	    }
1.42      ng       2850: 	    for (var i=0; i<radioButton.length; i++) {
                   2851: 		radioButton[i].checked=false;
1.109     matthew  2852: 		if (parseFloat(point) == i) {
1.42      ng       2853: 		    radioButton[i].checked=true;
                   2854: 		}
                   2855: 	    }
1.41      ng       2856: 
1.42      ng       2857: 	} else {
1.125     ng       2858: 	    textbox.value = parseFloat(point);
1.42      ng       2859: 	}
1.41      ng       2860: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2861: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2862: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2863: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2864: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2865: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2866: 	    if (saveval != "correct") {
                   2867: 		scorename.value = point;
1.43      ng       2868: 		if (selname[0].selected != true) {
                   2869: 		    selname[0].selected = true;
                   2870: 		}
1.42      ng       2871: 	    }
                   2872: 	}
1.125     ng       2873: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2874:     }
                   2875: 
                   2876:     function writeRadText(partid,weight) {
1.125     ng       2877: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2878: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2879:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2880: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2881: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2882: 	    for (var i=0; i<radioButton.length; i++) {
                   2883: 		radioButton[i].checked=false;
                   2884: 
                   2885: 	    }
                   2886: 	    textbox.value = "";
                   2887: 
                   2888: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2889: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2890: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2891: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2892: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2893: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2894: 		if ((saveval != "correct") || override) {
1.42      ng       2895: 		    scorename.value = "";
1.125     ng       2896: 		    if (selval[1].selected) {
                   2897: 			selname[1].selected = true;
                   2898: 		    } else {
                   2899: 			selname[2].selected = true;
                   2900: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   2901: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   2902: 		    }
1.42      ng       2903: 		}
                   2904: 	    }
1.43      ng       2905: 	} else {
                   2906: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2907: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2908: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2909: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2910: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2911: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2912: 		if ((saveval != "correct") || override) {
1.125     ng       2913: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       2914: 		    selname[0].selected = true;
                   2915: 		}
                   2916: 	    }
                   2917: 	}	    
1.42      ng       2918:     }
                   2919: 
                   2920:     function changeSelect(partid,user) {
1.125     ng       2921: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2922: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       2923: 	var point  = textbox.value;
1.125     ng       2924: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       2925: 
1.109     matthew  2926: 	if (isNaN(point) || parseFloat(point) < 0) {
                   2927: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       2928: 	    textbox.value = "";
                   2929: 	    return;
                   2930: 	}
1.109     matthew  2931: 	if (parseFloat(point) > parseFloat(weight)) {
                   2932: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2933: 			       ") greater than the weight of the part. Accept?");
                   2934: 	    if (resp == false) {
                   2935: 		textbox.value = "";
                   2936: 		return;
                   2937: 	    }
                   2938: 	}
1.42      ng       2939: 	selval[0].selected = true;
                   2940:     }
                   2941: 
                   2942:     function changeOneScore(partid,user) {
1.125     ng       2943: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2944: 	if (selval[1].selected || selval[2].selected) {
                   2945: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   2946: 	    if (selval[2].selected) {
                   2947: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   2948: 	    }
1.269     raeburn  2949:         }
1.42      ng       2950:     }
                   2951: 
                   2952:     function resetEntry(numpart) {
                   2953: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       2954: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   2955: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   2956: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   2957: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       2958: 	    for (var i=0; i<radioButton.length; i++) {
                   2959: 		radioButton[i].checked=false;
                   2960: 
                   2961: 	    }
                   2962: 	    textbox.value = "";
                   2963: 	    selval[0].selected = true;
                   2964: 
                   2965: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2966: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2967: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2968: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2969: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   2970: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   2971: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   2972: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2973: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2974: 		if (saveselval == "excused") {
1.43      ng       2975: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       2976: 		} else {
1.43      ng       2977: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       2978: 		}
                   2979: 	    }
1.41      ng       2980: 	}
1.42      ng       2981:     }
                   2982: 
1.41      ng       2983: </script>
                   2984: VIEWJAVASCRIPT
1.42      ng       2985: }
                   2986: 
1.44      ng       2987: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       2988: sub viewgrades {
                   2989:     my ($request) = shift;
                   2990:     &viewgrades_js($request);
1.41      ng       2991: 
1.324     albertel 2992:     my ($symb) = &get_symb($request);
1.168     albertel 2993:     #need to make sure we have the correct data for later EXT calls, 
                   2994:     #thus invalidate the cache
                   2995:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 2996:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   2997:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 2998:     &Apache::lonnet::clear_EXT_cache_status();
                   2999: 
1.398     albertel 3000:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   3001:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       3002: 
                   3003:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3004:     $result.=&jscriptNform($symb);
1.41      ng       3005: 
1.44      ng       3006:     #beginning of class grading form
1.41      ng       3007:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3008: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3009: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3010: 	&build_section_inputs().
1.257     albertel 3011: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   3012: 	'<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
                   3013: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3014: 
1.126     ng       3015:     my $sectionClass;
1.430     banghart 3016:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3017:     if ($env{'form.section'} eq 'all') {
1.126     ng       3018: 	$sectionClass='Class </h3>';
1.257     albertel 3019:     } elsif ($env{'form.section'} eq 'none') {
1.431     banghart 3020: 	$sectionClass=&mt('Students in no Section').'</h3>';
1.52      albertel 3021:     } else {
1.431     banghart 3022: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
1.52      albertel 3023:     }
1.431     banghart 3024:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
1.52      albertel 3025:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   3026: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       3027:     #radio buttons/text box for assigning points for a section or class.
                   3028:     #handles different parts of a problem
1.375     albertel 3029:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3030:     my %weight = ();
                   3031:     my $ctsparts = 0;
1.41      ng       3032:     $result.='<table border="0">';
1.45      ng       3033:     my %seen = ();
1.375     albertel 3034:     my @part_response_id = &flatten_responseType($responseType);
                   3035:     foreach my $part_response_id (@part_response_id) {
                   3036:     	my ($partid,$respid) = @{ $part_response_id };
                   3037: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3038: 	next if $seen{$partid};
                   3039: 	$seen{$partid}++;
1.375     albertel 3040: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3041: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3042: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3043: 
1.44      ng       3044: 	$result.='<input type="hidden" name="partid_'.
                   3045: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3046: 	$result.='<input type="hidden" name="weight_'.
                   3047: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3048: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 3049: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3050: 	$result.='<table border="0"><tr>';  
1.41      ng       3051: 	my $ctr = 0;
1.42      ng       3052: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3053: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3054: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3055: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3056: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3057: 	    $ctr++;
                   3058: 	}
                   3059: 	$result.='</tr></table>';
1.44      ng       3060: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3061: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3062: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3063: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   3064: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3065: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3066: 		$weight{$partid}.')"> '.
1.401     albertel 3067: 	    '<option selected="selected"> </option>'.
1.125     ng       3068: 	    '<option>excused</option>'.
1.265     www      3069: 	    '<option>reset status</option></select></td>'.
1.266     albertel 3070:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       3071: 	$ctsparts++;
1.41      ng       3072:     }
1.52      albertel 3073:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   3074: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3075:     $result.='<input type="button" value="Revert to Default" '.
1.417     albertel 3076: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
1.41      ng       3077: 
1.44      ng       3078:     #table listing all the students in a section/class
                   3079:     #header of table
1.126     ng       3080:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       3081:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       3082: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       3083: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 3084:     my (@parts) = sort(&getpartlist($symb));
                   3085:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3086:     my @partids = ();
1.41      ng       3087:     foreach my $part (@parts) {
                   3088: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3089: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3090: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3091: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3092:         push(@partids, $partid);
1.324     albertel 3093: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3094: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 3095: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   3096: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       3097: 	    next;
1.207     albertel 3098: 	} else {
                   3099: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3100: 	}
1.53      albertel 3101: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 3102: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       3103:     }
                   3104:     $result.='</tr>';
1.44      ng       3105: 
1.270     albertel 3106:     my %last_resets = 
                   3107: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3108: 
1.41      ng       3109:     #get info for each student
1.44      ng       3110:     #list all the students - with points and grade status
1.257     albertel 3111:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3112:     my $ctr = 0;
1.294     albertel 3113:     foreach (sort 
                   3114: 	     {
                   3115: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3116: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3117: 		 }
                   3118: 		 return $a cmp $b;
                   3119: 	     } (keys(%$fullname))) {
1.126     ng       3120: 	$ctr++;
1.324     albertel 3121: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3122: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3123:     }
                   3124:     $result.='</table></td></tr></table>';
                   3125:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3126:     $result.='<input type="button" value="Save" '.
1.417     albertel 3127: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3128:     if (scalar(%$fullname) eq 0) {
                   3129: 	my $colspan=3+scalar(@parts);
1.433     banghart 3130: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3131: 	$result='<span class="LC_warning">'.
                   3132: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
                   3133: 	        $section_display, $env{'form.Status'}).
                   3134: 	    '</span>';
1.96      albertel 3135:     }
1.324     albertel 3136:     $result.=&show_grading_menu_form($symb);
1.41      ng       3137:     return $result;
                   3138: }
                   3139: 
1.44      ng       3140: #--- call by previous routine to display each student
1.41      ng       3141: sub viewstudentgrade {
1.324     albertel 3142:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3143:     my ($uname,$udom) = split(/:/,$student);
                   3144:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3145:     my %aggregates = (); 
1.233     albertel 3146:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3147: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3148: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3149: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3150: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3151: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3152:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3153:     foreach my $apart (@$parts) {
                   3154: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3155: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3156:         $result.='<td align="center">';
1.269     raeburn  3157:         my ($aggtries,$totaltries);
                   3158:         unless (exists($aggregates{$part})) {
1.270     albertel 3159: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3160: 
                   3161: 	    $aggtries = $totaltries;
1.269     raeburn  3162:             if ($$last_resets{$part}) {  
1.270     albertel 3163:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3164: 					   $part);
                   3165:             }
1.269     raeburn  3166:             $result.='<input type="hidden" name="'.
                   3167:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3168:             $result.='<input type="hidden" name="'.
                   3169:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3170:             $aggregates{$part} = 1;
                   3171:         }
1.41      ng       3172: 	if ($type eq 'awarded') {
1.320     albertel 3173: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3174: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3175: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3176: 	    $result.='<input type="text" name="'.
1.89      albertel 3177: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3178: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3179: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3180: 	} elsif ($type eq 'solved') {
                   3181: 	    my ($status,$foo)=split(/_/,$score,2);
                   3182: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3183: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3184: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3185: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3186: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3187: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3188: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3189: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3190: 	    $result.='<option>reset status</option>';
1.126     ng       3191: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3192: 	} else {
                   3193: 	    $result.='<input type="hidden" name="'.
                   3194: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3195: 		    "\n";
1.233     albertel 3196: 	    $result.='<input type="text" name="'.
1.122     ng       3197: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3198: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3199: 	}
                   3200:     }
                   3201:     $result.='</tr>';
                   3202:     return $result;
1.38      ng       3203: }
                   3204: 
1.44      ng       3205: #--- change scores for all the students in a section/class
                   3206: #    record does not get update if unchanged
1.38      ng       3207: sub editgrades {
1.41      ng       3208:     my ($request) = @_;
                   3209: 
1.324     albertel 3210:     my $symb=&get_symb($request);
1.433     banghart 3211:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3212:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
                   3213:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
                   3214:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3215: 
1.44      ng       3216:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3217:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3218: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3219: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3220: 
                   3221:     my %scoreptr = (
                   3222: 		    'correct'  =>'correct_by_override',
                   3223: 		    'incorrect'=>'incorrect_by_override',
                   3224: 		    'excused'  =>'excused',
                   3225: 		    'ungraded' =>'ungraded_attempted',
                   3226: 		    'nothing'  => '',
                   3227: 		    );
1.257     albertel 3228:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3229: 
1.44      ng       3230:     my (@partid);
                   3231:     my %weight = ();
1.54      albertel 3232:     my %columns = ();
1.44      ng       3233:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3234: 
1.324     albertel 3235:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3236:     my $header;
1.257     albertel 3237:     while ($ctr < $env{'form.totalparts'}) {
                   3238: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3239: 	push @partid,$partid;
1.257     albertel 3240: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3241: 	$ctr++;
1.54      albertel 3242:     }
1.324     albertel 3243:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3244:     foreach my $partid (@partid) {
                   3245: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3246: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3247: 	$columns{$partid}=2;
                   3248: 	foreach my $stores (@parts) {
                   3249: 	    my ($part,$type) = &split_part_type($stores);
                   3250: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3251: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3252: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3253: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3254: 	    $display =~ s/Number of Attempts/Tries/;
                   3255: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3256: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3257: 	    $columns{$partid}+=2;
                   3258: 	}
                   3259:     }
                   3260:     foreach my $partid (@partid) {
1.324     albertel 3261: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3262: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3263: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3264: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3265: 
1.44      ng       3266:     }
                   3267:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3268:     $result .= $header;
1.44      ng       3269:     $result .= '</tr>'."\n";
1.93      albertel 3270:     my $noupdate;
1.126     ng       3271:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3272:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3273: 	my $line;
1.257     albertel 3274: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3275: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3276: 	my %newrecord;
                   3277: 	my $updateflag = 0;
1.281     albertel 3278: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3279: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3280: 	if (!&canmodify($usec)) {
1.126     ng       3281: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3282: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3283: 	    next;
                   3284: 	}
1.269     raeburn  3285:         my %aggregate = ();
                   3286:         my $aggregateflag = 0;
1.281     albertel 3287: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3288: 	foreach (@partid) {
1.257     albertel 3289: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3290: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3291: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3292: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3293: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3294: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3295: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3296: 	    my $score;
                   3297: 	    if ($partial eq '') {
1.257     albertel 3298: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3299: 	    } elsif ($partial > 0) {
                   3300: 		$score = 'correct_by_override';
                   3301: 	    } elsif ($partial == 0) {
                   3302: 		$score = 'incorrect_by_override';
                   3303: 	    }
1.257     albertel 3304: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3305: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3306: 
1.292     albertel 3307: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3308: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3309: 	    if ($dropMenu eq 'reset status' &&
                   3310: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3311: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3312: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3313: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3314: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3315: 		$updateflag = 1;
1.269     raeburn  3316:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3317:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3318:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3319:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3320:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3321:                     $aggregateflag = 1;
                   3322:                 }
1.139     albertel 3323: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3324: 		$updateflag = 1;
                   3325: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3326: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3327: 		$rec_update++;
1.125     ng       3328: 	    }
                   3329: 
1.93      albertel 3330: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3331: 		'<td align="center">'.$awarded.
                   3332: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3333: 
1.54      albertel 3334: 
                   3335: 	    my $partid=$_;
                   3336: 	    foreach my $stores (@parts) {
                   3337: 		my ($part,$type) = &split_part_type($stores);
                   3338: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3339: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3340: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3341: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3342: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3343: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3344: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3345: 		    $updateflag=1;
                   3346: 		}
1.93      albertel 3347: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3348: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3349: 	    }
1.44      ng       3350: 	}
1.93      albertel 3351: 	$line.='</tr>'."\n";
1.301     albertel 3352: 
                   3353: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3354: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3355: 
1.44      ng       3356: 	if ($updateflag) {
                   3357: 	    $count++;
1.257     albertel 3358: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3359: 				    $udom,$uname);
1.301     albertel 3360: 
                   3361: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3362: 					      $cnum,$udom,$uname)) {
                   3363: 		# need to figure out if should be in queue.
                   3364: 		my %record =  
                   3365: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3366: 					     $udom,$uname);
                   3367: 		my $all_graded = 1;
                   3368: 		my $none_graded = 1;
                   3369: 		foreach my $part (@parts) {
                   3370: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3371: 			$all_graded = 0;
                   3372: 		    } else {
                   3373: 			$none_graded = 0;
                   3374: 		    }
                   3375: 		}
                   3376: 
                   3377: 		if ($all_graded || $none_graded) {
                   3378: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3379: 							   $symb,$cdom,$cnum,
                   3380: 							   $udom,$uname);
                   3381: 		}
                   3382: 	    }
                   3383: 
1.126     ng       3384: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3385: 	    $updateCtr++;
1.93      albertel 3386: 	} else {
1.126     ng       3387: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3388: 	    $noupdateCtr++;
1.44      ng       3389: 	}
1.269     raeburn  3390:         if ($aggregateflag) {
                   3391:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3392: 				  $cdom,$cnum);
1.269     raeburn  3393:         }
1.93      albertel 3394:     }
                   3395:     if ($noupdate) {
1.126     ng       3396: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3397: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3398: 	$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       3399:     }
1.72      ng       3400:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3401: 	&show_grading_menu_form ($symb);
1.125     ng       3402:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3403: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3404: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3405:     return $title.$msg.$result;
1.5       albertel 3406: }
1.54      albertel 3407: 
                   3408: sub split_part_type {
                   3409:     my ($partstr) = @_;
                   3410:     my ($temp,@allparts)=split(/_/,$partstr);
                   3411:     my $type=pop(@allparts);
                   3412:     my $part=join('.',@allparts);
                   3413:     return ($part,$type);
                   3414: }
                   3415: 
1.44      ng       3416: #------------- end of section for handling grading by section/class ---------
                   3417: #
                   3418: #----------------------------------------------------------------------------
                   3419: 
1.5       albertel 3420: 
1.44      ng       3421: #----------------------------------------------------------------------------
                   3422: #
                   3423: #-------------------------- Next few routines handles grading by csv upload
                   3424: #
                   3425: #--- Javascript to handle csv upload
1.27      albertel 3426: sub csvupload_javascript_reverse_associate {
1.246     albertel 3427:     my $error1=&mt('You need to specify the username or ID');
                   3428:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3429:   return(<<ENDPICK);
                   3430:   function verify(vf) {
                   3431:     var foundsomething=0;
                   3432:     var founduname=0;
1.243     albertel 3433:     var foundID=0;
1.27      albertel 3434:     for (i=0;i<=vf.nfields.value;i++) {
                   3435:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3436:       if (i==0 && tw!=0) { foundID=1; }
                   3437:       if (i==1 && tw!=0) { founduname=1; }
                   3438:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3439:     }
1.246     albertel 3440:     if (founduname==0 && foundID==0) {
                   3441: 	alert('$error1');
                   3442: 	return;
1.27      albertel 3443:     }
                   3444:     if (foundsomething==0) {
1.246     albertel 3445: 	alert('$error2');
                   3446: 	return;
1.27      albertel 3447:     }
                   3448:     vf.submit();
                   3449:   }
                   3450:   function flip(vf,tf) {
                   3451:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3452:     var i;
                   3453:     for (i=0;i<=vf.nfields.value;i++) {
                   3454:       //can not pick the same destination field for both name and domain
                   3455:       if (((i ==0)||(i ==1)) && 
                   3456:           ((tf==0)||(tf==1)) && 
                   3457:           (i!=tf) &&
                   3458:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3459:         eval('vf.f'+i+'.selectedIndex=0;')
                   3460:       }
                   3461:     }
                   3462:   }
                   3463: ENDPICK
                   3464: }
                   3465: 
                   3466: sub csvupload_javascript_forward_associate {
1.246     albertel 3467:     my $error1=&mt('You need to specify the username or ID');
                   3468:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3469:   return(<<ENDPICK);
                   3470:   function verify(vf) {
                   3471:     var foundsomething=0;
                   3472:     var founduname=0;
1.243     albertel 3473:     var foundID=0;
1.27      albertel 3474:     for (i=0;i<=vf.nfields.value;i++) {
                   3475:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3476:       if (tw==1) { foundID=1; }
                   3477:       if (tw==2) { founduname=1; }
                   3478:       if (tw>3) { foundsomething=1; }
1.27      albertel 3479:     }
1.246     albertel 3480:     if (founduname==0 && foundID==0) {
                   3481: 	alert('$error1');
                   3482: 	return;
1.27      albertel 3483:     }
                   3484:     if (foundsomething==0) {
1.246     albertel 3485: 	alert('$error2');
                   3486: 	return;
1.27      albertel 3487:     }
                   3488:     vf.submit();
                   3489:   }
                   3490:   function flip(vf,tf) {
                   3491:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3492:     var i;
                   3493:     //can not pick the same destination field twice
                   3494:     for (i=0;i<=vf.nfields.value;i++) {
                   3495:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3496:         eval('vf.f'+i+'.selectedIndex=0;')
                   3497:       }
                   3498:     }
                   3499:   }
                   3500: ENDPICK
                   3501: }
                   3502: 
1.26      albertel 3503: sub csvuploadmap_header {
1.324     albertel 3504:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3505:     my $javascript;
1.257     albertel 3506:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3507: 	$javascript=&csvupload_javascript_reverse_associate();
                   3508:     } else {
                   3509: 	$javascript=&csvupload_javascript_forward_associate();
                   3510:     }
1.45      ng       3511: 
1.324     albertel 3512:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3513:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3514:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3515:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3516:     $request->print(<<ENDPICK);
1.26      albertel 3517: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3518: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3519: $result
1.326     albertel 3520: <hr />
1.26      albertel 3521: <h3>Identify fields</h3>
                   3522: Total number of records found in file: $distotal <hr />
                   3523: Enter as many fields as you can. The system will inform you and bring you back
                   3524: to this page if the data selected is insufficient to run your class.<hr />
                   3525: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3526: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3527: <input type="hidden" name="associate"  value="" />
                   3528: <input type="hidden" name="phase"      value="three" />
                   3529: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3530: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3531: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3532: <input type="hidden" name="upfile_associate" 
1.257     albertel 3533:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3534: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3535: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3536: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3537: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3538: <hr />
                   3539: <script type="text/javascript" language="Javascript">
                   3540: $javascript
                   3541: </script>
                   3542: ENDPICK
1.118     ng       3543:     return '';
1.26      albertel 3544: 
                   3545: }
                   3546: 
                   3547: sub csvupload_fields {
1.324     albertel 3548:     my ($symb) = @_;
                   3549:     my (@parts) = &getpartlist($symb);
1.243     albertel 3550:     my @fields=(['ID','Student ID'],
                   3551: 		['username','Student Username'],
                   3552: 		['domain','Student Domain']);
1.324     albertel 3553:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3554:     foreach my $part (sort(@parts)) {
                   3555: 	my @datum;
                   3556: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3557: 	my $name=$part;
                   3558: 	if  (!$display) { $display = $name; }
                   3559: 	@datum=($name,$display);
1.244     albertel 3560: 	if ($name=~/^stores_(.*)_awarded/) {
                   3561: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3562: 	}
1.41      ng       3563: 	push(@fields,\@datum);
                   3564:     }
                   3565:     return (@fields);
1.26      albertel 3566: }
                   3567: 
                   3568: sub csvuploadmap_footer {
1.41      ng       3569:     my ($request,$i,$keyfields) =@_;
                   3570:     $request->print(<<ENDPICK);
1.26      albertel 3571: </table>
                   3572: <input type="hidden" name="nfields" value="$i" />
                   3573: <input type="hidden" name="keyfields" value="$keyfields" />
                   3574: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3575: </form>
                   3576: ENDPICK
                   3577: }
                   3578: 
1.283     albertel 3579: sub checkforfile_js {
1.86      ng       3580:     my $result =<<CSVFORMJS;
                   3581: <script type="text/javascript" language="javascript">
                   3582:     function checkUpload(formname) {
                   3583: 	if (formname.upfile.value == "") {
                   3584: 	    alert("Please use the browse button to select a file from your local directory.");
                   3585: 	    return false;
                   3586: 	}
                   3587: 	formname.submit();
                   3588:     }
                   3589:     </script>
                   3590: CSVFORMJS
1.283     albertel 3591:     return $result;
                   3592: }
                   3593: 
                   3594: sub upcsvScores_form {
                   3595:     my ($request) = shift;
1.324     albertel 3596:     my ($symb)=&get_symb($request);
1.283     albertel 3597:     if (!$symb) {return '';}
                   3598:     my $result=&checkforfile_js();
1.257     albertel 3599:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3600:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3601:     $result.=$table;
1.326     albertel 3602:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3603:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3604:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3605: 	'.</b></td></tr>'."\n";
                   3606:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3607:     my $upload=&mt("Upload Scores");
1.86      ng       3608:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3609:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3610:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3611:     $result.=<<ENDUPFORM;
1.106     albertel 3612: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3613: <input type="hidden" name="symb" value="$symb" />
                   3614: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3615: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3616: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3617: $upfile_select
1.370     www      3618: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3619: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3620: </form>
                   3621: ENDUPFORM
1.370     www      3622:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3623:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3624:     .'</td></tr></table>'."\n";
1.86      ng       3625:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3626:     $result.=&show_grading_menu_form($symb);
1.86      ng       3627:     return $result;
                   3628: }
                   3629: 
                   3630: 
1.26      albertel 3631: sub csvuploadmap {
1.41      ng       3632:     my ($request)= @_;
1.324     albertel 3633:     my ($symb)=&get_symb($request);
1.41      ng       3634:     if (!$symb) {return '';}
1.72      ng       3635: 
1.41      ng       3636:     my $datatoken;
1.257     albertel 3637:     if (!$env{'form.datatoken'}) {
1.41      ng       3638: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3639:     } else {
1.257     albertel 3640: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3641: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3642:     }
1.41      ng       3643:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3644:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3645:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3646:     my ($i,$keyfields);
                   3647:     if (@records) {
1.324     albertel 3648: 	my @fields=&csvupload_fields($symb);
1.45      ng       3649: 
1.257     albertel 3650: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3651: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3652: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3653: 							  \@fields);
                   3654: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3655: 	    chop($keyfields);
                   3656: 	} else {
                   3657: 	    unshift(@fields,['none','']);
                   3658: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3659: 							    \@fields);
1.311     banghart 3660:             foreach my $rec (@records) {
                   3661:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3662:                 if (%temp) {
                   3663:                     $keyfields=join(',',sort(keys(%temp)));
                   3664:                     last;
                   3665:                 }
                   3666:             }
1.41      ng       3667: 	}
                   3668:     }
                   3669:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3670:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3671: 
1.41      ng       3672:     return '';
1.27      albertel 3673: }
                   3674: 
1.246     albertel 3675: sub csvuploadoptions {
1.41      ng       3676:     my ($request)= @_;
1.324     albertel 3677:     my ($symb)=&get_symb($request);
1.257     albertel 3678:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3679:     my $ignore=&mt('Ignore First Line');
                   3680:     $request->print(<<ENDPICK);
                   3681: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3682: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3683: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3684: <!--
1.246     albertel 3685: <p>
                   3686: <label>
                   3687:    <input type="checkbox" name="show_full_results" />
                   3688:    Show a table of all changes
                   3689: </label>
                   3690: </p>
1.302     albertel 3691: -->
1.246     albertel 3692: <p>
                   3693: <label>
                   3694:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3695:    Overwrite any existing score
                   3696: </label>
                   3697: </p>
                   3698: ENDPICK
                   3699:     my %fields=&get_fields();
                   3700:     if (!defined($fields{'domain'})) {
1.257     albertel 3701: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3702: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3703:     }
1.257     albertel 3704:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3705: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3706: 	my $cleankey=$1;
                   3707: 	if ($cleankey eq 'command') { next; }
                   3708: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3709: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3710:     }
                   3711:     # FIXME do a check for any duplicated user ids...
                   3712:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3713:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3714: <hr /></form>'."\n");
1.324     albertel 3715:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3716:     return '';
                   3717: }
                   3718: 
                   3719: sub get_fields {
                   3720:     my %fields;
1.257     albertel 3721:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3722:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3723: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3724: 	    if ($env{'form.f'.$i} ne 'none') {
                   3725: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3726: 	    }
                   3727: 	} else {
1.257     albertel 3728: 	    if ($env{'form.f'.$i} ne 'none') {
                   3729: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3730: 	    }
                   3731: 	}
1.27      albertel 3732:     }
1.246     albertel 3733:     return %fields;
                   3734: }
                   3735: 
                   3736: sub csvuploadassign {
                   3737:     my ($request)= @_;
1.324     albertel 3738:     my ($symb)=&get_symb($request);
1.246     albertel 3739:     if (!$symb) {return '';}
1.345     bowersj2 3740:     my $error_msg = '';
1.246     albertel 3741:     &Apache::loncommon::load_tmp_file($request);
                   3742:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3743:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3744:     my %fields=&get_fields();
1.41      ng       3745:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3746:     my $courseid=$env{'request.course.id'};
1.97      albertel 3747:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3748:     my @notallowed;
1.41      ng       3749:     my @skipped;
                   3750:     my $countdone=0;
                   3751:     foreach my $grade (@gradedata) {
                   3752: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3753: 	my $domain;
                   3754: 	if ($entries{$fields{'domain'}}) {
                   3755: 	    $domain=$entries{$fields{'domain'}};
                   3756: 	} else {
1.257     albertel 3757: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3758: 	}
1.243     albertel 3759: 	$domain=~s/\s//g;
1.41      ng       3760: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3761: 	$username=~s/\s//g;
1.243     albertel 3762: 	if (!$username) {
                   3763: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3764: 	    $id=~s/\s//g;
1.243     albertel 3765: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3766: 	    $username=$ids{$id};
                   3767: 	}
1.41      ng       3768: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3769: 	    my $id=$entries{$fields{'ID'}};
                   3770: 	    $id=~s/\s//g;
                   3771: 	    if ($id) {
                   3772: 		push(@skipped,"$id:$domain");
                   3773: 	    } else {
                   3774: 		push(@skipped,"$username:$domain");
                   3775: 	    }
1.41      ng       3776: 	    next;
                   3777: 	}
1.108     albertel 3778: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3779: 	if (!&canmodify($usec)) {
                   3780: 	    push(@notallowed,"$username:$domain");
                   3781: 	    next;
                   3782: 	}
1.244     albertel 3783: 	my %points;
1.41      ng       3784: 	my %grades;
                   3785: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3786: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3787: 		$dest eq 'domain') { next; }
                   3788: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3789: 	    if ($dest=~/stores_(.*)_points/) {
                   3790: 		my $part=$1;
                   3791: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3792: 					      $symb,$domain,$username);
1.345     bowersj2 3793:                 if ($wgt) {
                   3794:                     $entries{$fields{$dest}}=~s/\s//g;
                   3795:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3796:                     my $award='correct_by_override';
                   3797:                     $grades{"resource.$part.awarded"}=$pcr;
                   3798:                     $grades{"resource.$part.solved"}=$award;
                   3799:                     $points{$part}=1;
                   3800:                 } else {
                   3801:                     $error_msg = "<br />" .
                   3802:                         &mt("Some point values were assigned"
                   3803:                             ." for problems with a weight "
                   3804:                             ."of zero. These values were "
                   3805:                             ."ignored.");
                   3806:                 }
1.244     albertel 3807: 	    } else {
                   3808: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3809: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3810: 		my $store_key=$dest;
                   3811: 		$store_key=~s/^stores/resource/;
                   3812: 		$store_key=~s/_/\./g;
                   3813: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3814: 	    }
1.41      ng       3815: 	}
1.398     albertel 3816: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3817: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.244     albertel 3818: #	&Apache::lonnet::logthis(" storing ".(join('-',%grades)));
1.302     albertel 3819: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3820: 					   $env{'request.course.id'},
                   3821: 					   $domain,$username);
                   3822: 	if ($result eq 'ok') {
                   3823: 	    $request->print('.');
                   3824: 	} else {
                   3825: 	    $request->print("<p>
1.398     albertel 3826:                               <span class=\"LC_error\">
                   3827:                                  Failed to save student $username:$domain.
                   3828:                                  Message when trying to save was ($result)
                   3829:                               </span>
1.302     albertel 3830:                              </p>" );
                   3831: 	}
1.41      ng       3832: 	$request->rflush();
                   3833: 	$countdone++;
                   3834:     }
1.398     albertel 3835:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3836:     if (@skipped) {
1.398     albertel 3837: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3838: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3839:     }
                   3840:     if (@notallowed) {
1.398     albertel 3841: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3842: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3843:     }
1.106     albertel 3844:     $request->print("<br />\n");
1.324     albertel 3845:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3846:     return $error_msg;
1.26      albertel 3847: }
1.44      ng       3848: #------------- end of section for handling csv file upload ---------
                   3849: #
                   3850: #-------------------------------------------------------------------
                   3851: #
1.122     ng       3852: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3853: #
                   3854: #--- Select a page/sequence and a student to grade
1.68      ng       3855: sub pickStudentPage {
                   3856:     my ($request) = shift;
                   3857: 
                   3858:     $request->print(<<LISTJAVASCRIPT);
                   3859: <script type="text/javascript" language="javascript">
                   3860: 
                   3861: function checkPickOne(formname) {
1.76      ng       3862:     if (radioSelection(formname.student) == null) {
1.68      ng       3863: 	alert("Please select the student you wish to grade.");
                   3864: 	return;
                   3865:     }
1.125     ng       3866:     ptr = pullDownSelection(formname.selectpage);
                   3867:     formname.page.value = formname["page"+ptr].value;
                   3868:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3869:     formname.submit();
                   3870: }
                   3871: 
                   3872: </script>
                   3873: LISTJAVASCRIPT
1.118     ng       3874:     &commonJSfunctions($request);
1.324     albertel 3875:     my ($symb) = &get_symb($request);
1.257     albertel 3876:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3877:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3878:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3879: 
1.398     albertel 3880:     my $result='<h3><span class="LC_info">&nbsp;'.
                   3881: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       3882: 
1.80      ng       3883:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3884:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 3885:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 3886:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3887: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3888: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3889:     my $ctr=0;
1.68      ng       3890:     foreach (@$titles) {
                   3891: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3892: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 3893: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       3894: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3895: 	$ctr++;
1.68      ng       3896:     }
1.326     albertel 3897:     $result.= '</select>'."<br />\n";
1.70      ng       3898:     $ctr=0;
                   3899:     foreach (@$titles) {
                   3900: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3901: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3902: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3903: 	$ctr++;
                   3904:     }
1.72      ng       3905:     $result.='<input type="hidden" name="page" />'."\n".
                   3906: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3907: 
1.401     albertel 3908:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 3909: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       3910: 
1.71      ng       3911:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 3912: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 3913: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 3914: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.432     banghart 3915:     
                   3916:     $result.=&build_section_inputs();
                   3917:     $result.='<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.72      ng       3918: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 3919: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 3920: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       3921: 
1.382     albertel 3922:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   3923: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   3924: 
1.80      ng       3925:     $result.='&nbsp;<input type="button" '.
1.126     ng       3926: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       3927: 
1.68      ng       3928:     $request->print($result);
                   3929: 
1.326     albertel 3930:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       3931: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3932: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       3933: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3934: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       3935: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3936: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       3937:  
1.76      ng       3938:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       3939:     my $ptr = 1;
1.294     albertel 3940:     foreach my $student (sort 
                   3941: 			 {
                   3942: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3943: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3944: 			     }
                   3945: 			     return $a cmp $b;
                   3946: 			 } (keys(%$fullname))) {
1.68      ng       3947: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       3948: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   3949: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 3950: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   3951: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       3952: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       3953: 	$ptr++;
                   3954:     }
1.381     albertel 3955:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   3956:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       3957:     $studentTable.='<input type="button" '.
                   3958: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       3959: 
1.324     albertel 3960:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       3961:     $request->print($studentTable);
                   3962: 
                   3963:     return '';
                   3964: }
                   3965: 
                   3966: sub getSymbMap {
1.132     bowersj2 3967:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       3968: 
                   3969:     my %symbx = ();
                   3970:     my @titles = ();
1.117     bowersj2 3971:     my $minder = 0;
                   3972: 
                   3973:     # Gather every sequence that has problems.
1.240     albertel 3974:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   3975: 					       1,0,1);
1.117     bowersj2 3976:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 3977: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 3978: 	    my $title = $minder.'.'.
                   3979: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   3980: 	    push(@titles, $title); # minder in case two titles are identical
                   3981: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 3982: 	    $minder++;
1.241     albertel 3983: 	}
1.68      ng       3984:     }
                   3985:     return \@titles,\%symbx;
                   3986: }
                   3987: 
1.72      ng       3988: #
                   3989: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       3990: sub displayPage {
                   3991:     my ($request) = shift;
                   3992: 
1.324     albertel 3993:     my ($symb) = &get_symb($request);
1.257     albertel 3994:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3995:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3996:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3997:     my $pageTitle = $env{'form.page'};
1.103     albertel 3998:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 3999:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4000:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4001: 
                   4002:     #need to make sure we have the correct data for later EXT calls, 
                   4003:     #thus invalidate the cache
                   4004:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4005:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4006:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4007:     &Apache::lonnet::clear_EXT_cache_status();
                   4008: 
1.103     albertel 4009:     if (!&canview($usec)) {
1.398     albertel 4010: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 4011: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4012: 	return;
                   4013:     }
1.398     albertel 4014:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4015:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       4016: 	'</h3>'."\n";
1.382     albertel 4017:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4018: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   4019:     } else {
                   4020: 	delete($env{'form.CODE'});
                   4021:     }
1.71      ng       4022:     &sub_page_js($request);
                   4023:     $request->print($result);
                   4024: 
1.132     bowersj2 4025:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4026:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4027:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4028:     if (!$map) {
1.398     albertel 4029: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4030: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4031: 	return; 
                   4032:     }
1.68      ng       4033:     my $iterator = $navmap->getIterator($map->map_start(),
                   4034: 					$map->map_finish());
                   4035: 
1.71      ng       4036:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4037: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4038: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4039: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4040: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4041: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4042: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4043: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4044: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4045: 
1.382     albertel 4046:     if (defined($env{'form.CODE'})) {
                   4047: 	$studentTable.=
                   4048: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4049:     }
1.381     albertel 4050:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4051: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4052: 	'/check.gif" height="16" border="0" />';
                   4053: 
1.118     ng       4054:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4055: 	' symbol.'."\n".
1.71      ng       4056: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4057: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4058: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4059: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4060: 
1.329     albertel 4061:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4062:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4063:     $iterator->next(); # skip the first BEGIN_MAP
                   4064:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4065:     while ($depth > 0) {
1.68      ng       4066:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4067:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4068: 
1.385     albertel 4069:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4070: 	    my $parts = $curRes->parts();
1.68      ng       4071:             my $title = $curRes->compTitle();
1.71      ng       4072: 	    my $symbx = $curRes->symb();
1.196     albertel 4073: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4074: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4075: 	    $studentTable.='<td valign="top">';
1.382     albertel 4076: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4077: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4078: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4079: 					     undef,'both',\%form);
1.71      ng       4080: 	    } else {
1.382     albertel 4081: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4082: 		$companswer =~ s|<form(.*?)>||g;
                   4083: 		$companswer =~ s|</form>||g;
1.71      ng       4084: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4085: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4086: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4087: #		}
1.116     ng       4088: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4089: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4090: 	    }
                   4091: 
1.257     albertel 4092: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4093: 
1.257     albertel 4094: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4095: 		if ($record{'version'} eq '') {
1.398     albertel 4096: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4097: 		} else {
1.116     ng       4098: 		    my %responseType = ();
                   4099: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4100: 			my @responseIds =$curRes->responseIds($partid);
                   4101: 			my @responseType =$curRes->responseType($partid);
                   4102: 			my %responseIds;
                   4103: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4104: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4105: 			}
                   4106: 			$responseType{$partid} = \%responseIds;
1.116     ng       4107: 		    }
1.148     albertel 4108: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4109: 
1.71      ng       4110: 		}
1.257     albertel 4111: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4112: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4113: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4114: 									$env{'request.course.id'},
1.71      ng       4115: 									'','.submission');
                   4116:  
                   4117: 	    }
1.103     albertel 4118: 	    if (&canmodify($usec)) {
                   4119: 		foreach my $partid (@{$parts}) {
                   4120: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4121: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4122: 		    $question++;
                   4123: 		}
1.196     albertel 4124: 		$prob++;
1.71      ng       4125: 	    }
                   4126: 	    $studentTable.='</td></tr>';
1.68      ng       4127: 
1.103     albertel 4128: 	}
1.68      ng       4129:         $curRes = $iterator->next();
                   4130:     }
                   4131: 
1.381     albertel 4132:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4133: 	'<input type="button" value="Save" '.
1.381     albertel 4134: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4135: 	'</form>'."\n";
1.324     albertel 4136:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4137:     $request->print($studentTable);
                   4138: 
                   4139:     return '';
1.119     ng       4140: }
                   4141: 
                   4142: sub displaySubByDates {
1.148     albertel 4143:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4144:     my $isCODE=0;
1.335     albertel 4145:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4146:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4147:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4148: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4149: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4150: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4151: 	'<td><b>Submission</b></td>'.
                   4152: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4153:     my ($version);
                   4154:     my %mark;
1.148     albertel 4155:     my %orders;
1.119     ng       4156:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4157:     if (!exists($$record{'1:timestamp'})) {
1.398     albertel 4158: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
1.147     albertel 4159:     }
1.335     albertel 4160: 
                   4161:     my $interaction;
1.119     ng       4162:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4163: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4164: 	if (exists($$record{$version.':resource.0.version'})) {
                   4165: 	    $interaction = $$record{$version.':resource.0.version'};
                   4166: 	}
                   4167: 
                   4168: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4169: 		             : "$version:resource");
                   4170: 	#&Apache::lonnet::logthis(" got $where");
1.119     ng       4171: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4172: 	if ($isCODE) {
                   4173: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4174: 	}
1.119     ng       4175: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4176: 	my @displaySub = ();
                   4177: 	foreach my $partid (@{$parts}) {
1.335     albertel 4178: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4179: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4180: 	    
                   4181: 
1.122     ng       4182: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4183: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4184: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4185: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4186: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4187: 
                   4188: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4189: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   4190: 		    #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
1.207     albertel 4191: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.398     albertel 4192: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
                   4193: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4194: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4195: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4196: 		    } else {
                   4197: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4198: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4199: 		    }
1.335     albertel 4200: 		    my $responseType=($isTask ? 'Task'
                   4201:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4202: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4203: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4204: 			$orders{$partid}->{$responseId}=
                   4205: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4206: 		    }
1.147     albertel 4207: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4208: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4209: 		}
                   4210: 	    }
1.335     albertel 4211: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4212: 		$displaySub[1].='Checked in by '.
                   4213: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4214: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4215: 		    '<br />';
                   4216: 	    }
                   4217: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4218: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4219: 		    lc($$record{"$where.$partid.award"}).' '.
                   4220: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4221: 		    '<br />';
                   4222: 	    }
1.335     albertel 4223: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4224: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4225: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4226: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4227: 		$displaySub[2].=
                   4228: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4229: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4230: 	    }
                   4231: 	}
                   4232: 	# needed because old essay regrader has not parts info
                   4233: 	if (exists $$record{"$version:resource.regrader"}) {
                   4234: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4235: 	}
                   4236: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4237: 	if ($displaySub[2]) {
                   4238: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4239: 	}
1.382     albertel 4240: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4241:     
1.119     ng       4242:     }
                   4243:     $studentTable.='</table></td></tr></table>';
                   4244:     return $studentTable;
1.71      ng       4245: }
                   4246: 
                   4247: sub updateGradeByPage {
                   4248:     my ($request) = shift;
                   4249: 
1.257     albertel 4250:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4251:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4252:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4253:     my $pageTitle = $env{'form.page'};
1.103     albertel 4254:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4255:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4256:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4257:     if (!&canmodify($usec)) {
1.398     albertel 4258: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4259: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4260: 	return;
                   4261:     }
1.398     albertel 4262:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4263:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4264: 	'</h3>'."\n";
1.70      ng       4265: 
1.68      ng       4266:     $request->print($result);
                   4267: 
1.132     bowersj2 4268:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4269:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4270:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4271:     if (!$map) {
1.398     albertel 4272: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4273: 	my ($symb)=&get_symb($request);
                   4274: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4275: 	return; 
                   4276:     }
1.71      ng       4277:     my $iterator = $navmap->getIterator($map->map_start(),
                   4278: 					$map->map_finish());
1.70      ng       4279: 
1.71      ng       4280:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4281: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4282: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4283: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4284: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4285: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4286: 
                   4287:     $iterator->next(); # skip the first BEGIN_MAP
                   4288:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4289:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4290:     while ($depth > 0) {
1.71      ng       4291:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4292:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4293: 
1.385     albertel 4294:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4295: 	    my $parts = $curRes->parts();
1.71      ng       4296:             my $title = $curRes->compTitle();
                   4297: 	    my $symbx = $curRes->symb();
1.196     albertel 4298: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4299: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4300: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4301: 
                   4302: 	    my %newrecord=();
                   4303: 	    my @displayPts=();
1.269     raeburn  4304:             my %aggregate = ();
                   4305:             my $aggregateflag = 0;
1.71      ng       4306: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4307: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4308: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4309: 
1.257     albertel 4310: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4311: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4312: 		my $partial = $newpts/$wgt;
                   4313: 		my $score;
                   4314: 		if ($partial > 0) {
                   4315: 		    $score = 'correct_by_override';
1.125     ng       4316: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4317: 		    $score = 'incorrect_by_override';
                   4318: 		}
1.257     albertel 4319: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4320: 		if ($dropMenu eq 'excused') {
1.71      ng       4321: 		    $partial = '';
                   4322: 		    $score = 'excused';
1.125     ng       4323: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4324: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4325: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4326: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4327: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4328: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4329: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4330: 		    $changeflag++;
                   4331: 		    $newpts = '';
1.269     raeburn  4332:                     
                   4333:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4334:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4335:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4336:                     if ($aggtries > 0) {
                   4337:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4338:                         $aggregateflag = 1;
                   4339:                     }
1.71      ng       4340: 		}
1.324     albertel 4341: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4342: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4343: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4344: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4345: 		    '&nbsp;<br />';
1.207     albertel 4346: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4347: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4348: 		    '&nbsp;<br />';
1.71      ng       4349: 		$question++;
1.380     albertel 4350: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4351: 
1.71      ng       4352: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4353: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4354: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4355: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4356: 
                   4357: 		$changeflag++;
                   4358: 	    }
                   4359: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4360: 		my %record = 
                   4361: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4362: 					     $udom,$uname);
                   4363: 
                   4364: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4365: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4366: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4367: 		    $newrecord{'resource.CODE'} = '';
                   4368: 		}
1.257     albertel 4369: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4370: 					$udom,$uname);
1.382     albertel 4371: 		%record = &Apache::lonnet::restore($symbx,
                   4372: 						   $env{'request.course.id'},
                   4373: 						   $udom,$uname);
1.380     albertel 4374: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4375: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4376: 	    }
1.380     albertel 4377: 	    
1.269     raeburn  4378:             if ($aggregateflag) {
                   4379:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4380:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4381:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4382:             }
1.125     ng       4383: 
1.71      ng       4384: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4385: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4386: 		'</tr>';
1.68      ng       4387: 
1.196     albertel 4388: 	    $prob++;
1.68      ng       4389: 	}
1.71      ng       4390:         $curRes = $iterator->next();
1.68      ng       4391:     }
1.98      albertel 4392: 
1.71      ng       4393:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4394:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4395:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4396: 		  'The scores were changed for '.
                   4397: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4398:     $request->print($grademsg.$studentTable);
1.68      ng       4399: 
1.70      ng       4400:     return '';
                   4401: }
                   4402: 
1.72      ng       4403: #-------- end of section for handling grading by page/sequence ---------
                   4404: #
                   4405: #-------------------------------------------------------------------
                   4406: 
1.75      albertel 4407: #--------------------Scantron Grading-----------------------------------
                   4408: #
                   4409: #------ start of section for handling grading by page/sequence ---------
                   4410: 
1.423     albertel 4411: =pod
                   4412: 
                   4413: =head1 Bubble sheet grading routines
                   4414: 
1.424     albertel 4415:   For this documentation:
                   4416: 
                   4417:    'scanline' refers to the full line of characters
                   4418:    from the file that we are parsing that represents one entire sheet
                   4419: 
                   4420:    'bubble line' refers to the data
                   4421:    representing the line of bubbles that are on the physical bubble sheet
                   4422: 
                   4423: 
                   4424: The overall process is that a scanned in bubble sheet data is uploaded
                   4425: into a course. When a user wants to grade, they select a
                   4426: sequence/folder of resources, a file of bubble sheet info, and pick
                   4427: one of the predefined configurations for what each scanline looks
                   4428: like.
                   4429: 
                   4430: Next each scanline is checked for any errors of either 'missing
                   4431: bubbles' (it's an error because it may have been missed scanned
                   4432: because too light bubbling), 'double bubble' (each bubble line should
                   4433: have no more that one letter picked), invalid or duplicated CODE,
                   4434: invalid student ID
                   4435: 
                   4436: If the CODE option is used that determines the randomization of the
                   4437: homework problems, either way the student ID is looked up into a
                   4438: username:domain.
                   4439: 
                   4440: During the validation phase the instructor can choose to skip scanlines. 
                   4441: 
                   4442: After the validation phase, there is now 3 bubble sheet files
                   4443: 
                   4444:   scantron_original_filename (unmodified original file)
                   4445:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4446:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4447: 
                   4448: Also there is a separate hash nohist_scantrondata that contains extra
                   4449: correction information that isn't representable in the bubble sheet
                   4450: file (see &scantron_getfile() for more information)
                   4451: 
                   4452: After all scanlines are either valid, marked as valid or skipped, then
                   4453: foreach line foreach problem in the picked sequence, an ssi request is
                   4454: made that simulates a user submitting their selected letter(s) against
                   4455: the homework problem.
1.423     albertel 4456: 
                   4457: =over 4
                   4458: 
                   4459: =cut
                   4460: 
                   4461: 
                   4462: =pod 
                   4463: 
                   4464: =item defaultFormData
                   4465: 
                   4466:   Returns html hidden inputs used to hold context/default values.
                   4467: 
                   4468:  Arguments:
                   4469:   $symb - $symb of the current resource 
                   4470: 
                   4471: =cut
1.422     foxr     4472: 
1.81      albertel 4473: sub defaultFormData {
1.324     albertel 4474:     my ($symb)=@_;
1.81      albertel 4475:     return '
1.418     albertel 4476:       <input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4477:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4478:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4479: }
                   4480: 
1.423     albertel 4481: =pod 
                   4482: 
                   4483: =item getSequenceDropDown
                   4484: 
                   4485:    Return html dropdown of possible sequences to grade
                   4486:  
                   4487:  Arguments:
                   4488:    $symb - $symb of the current resource 
                   4489: 
                   4490: =cut
1.422     foxr     4491: 
1.75      albertel 4492: sub getSequenceDropDown {
1.423     albertel 4493:     my ($symb)=@_;
1.75      albertel 4494:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4495:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4496:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4497:     my $ctr=0;
                   4498:     foreach (@$titles) {
                   4499: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4500: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4501: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4502: 	    '>'.$showtitle.'</option>'."\n";
                   4503: 	$ctr++;
                   4504:     }
                   4505:     $result.= '</select>';
                   4506:     return $result;
                   4507: }
                   4508: 
1.423     albertel 4509: 
                   4510: =pod 
                   4511: 
                   4512: =item scantron_filenames
                   4513: 
                   4514:    Returns a list of the scantron files in the current course 
                   4515: 
                   4516: =cut
1.422     foxr     4517: 
1.202     albertel 4518: sub scantron_filenames {
1.257     albertel 4519:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4520:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4521:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4522: 				    &propath($cdom,$cname));
1.202     albertel 4523:     my @possiblenames;
1.201     albertel 4524:     foreach my $filename (sort(@files)) {
1.157     albertel 4525: 	($filename)=split(/&/,$filename);
                   4526: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4527: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4528: 	push(@possiblenames,$filename);
                   4529:     }
                   4530:     return @possiblenames;
                   4531: }
                   4532: 
1.423     albertel 4533: =pod 
                   4534: 
                   4535: =item scantron_uploads
                   4536: 
                   4537:    Returns  html drop-down list of scantron files in current course.
                   4538: 
                   4539:  Arguments:
                   4540:    $file2grade - filename to set as selected in the dropdown
                   4541: 
                   4542: =cut
1.422     foxr     4543: 
1.202     albertel 4544: sub scantron_uploads {
1.209     ng       4545:     my ($file2grade) = @_;
1.202     albertel 4546:     my $result=	'<select name="scantron_selectfile">';
                   4547:     $result.="<option></option>";
                   4548:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4549: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4550:     }
                   4551:     $result.="</select>";
                   4552:     return $result;
                   4553: }
                   4554: 
1.423     albertel 4555: =pod 
                   4556: 
                   4557: =item scantron_scantab
                   4558: 
                   4559:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4560:   file.
                   4561: 
                   4562: =cut
1.422     foxr     4563: 
1.82      albertel 4564: sub scantron_scantab {
                   4565:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4566:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4567:     $result.='<option></option>'."\n";
1.82      albertel 4568:     foreach my $line (<$fh>) {
                   4569: 	my ($name,$descrip)=split(/:/,$line);
                   4570: 	if ($name =~ /^\#/) { next; }
                   4571: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4572:     }
                   4573:     $result.='</select>'."\n";
                   4574: 
                   4575:     return $result;
                   4576: }
                   4577: 
1.423     albertel 4578: =pod 
                   4579: 
                   4580: =item scantron_CODElist
                   4581: 
                   4582:   Returns html drop down of the saved CODE lists from current course,
                   4583:   generated from earlier printings.
                   4584: 
                   4585: =cut
1.422     foxr     4586: 
1.186     albertel 4587: sub scantron_CODElist {
1.257     albertel 4588:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4589:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4590:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4591:     my $namechoice='<option></option>';
1.225     albertel 4592:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4593: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4594: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4595: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4596:     }
                   4597:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4598:     return $namechoice;
                   4599: }
                   4600: 
1.423     albertel 4601: =pod 
                   4602: 
                   4603: =item scantron_CODEunique
                   4604: 
                   4605:   Returns the html for "Each CODE to be used once" radio.
                   4606: 
                   4607: =cut
1.422     foxr     4608: 
1.186     albertel 4609: sub scantron_CODEunique {
1.381     albertel 4610:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4611:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4612:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4613:                 </span>
                   4614:                 <span style="white-space: nowrap;">
1.272     albertel 4615:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4616:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4617:                 </span>';
1.186     albertel 4618:     return $result;
                   4619: }
1.423     albertel 4620: 
                   4621: =pod 
                   4622: 
                   4623: =item scantron_selectphase
                   4624: 
                   4625:   Generates the initial screen to start the bubble sheet process.
                   4626:   Allows for - starting a grading run.
1.424     albertel 4627:              - downloading existing scan data (original, corrected
1.423     albertel 4628:                                                 or skipped info)
                   4629: 
                   4630:              - uploading new scan data
                   4631: 
                   4632:  Arguments:
                   4633:   $r          - The Apache request object
                   4634:   $file2grade - name of the file that contain the scanned data to score
                   4635: 
                   4636: =cut
1.186     albertel 4637: 
1.75      albertel 4638: sub scantron_selectphase {
1.209     ng       4639:     my ($r,$file2grade) = @_;
1.324     albertel 4640:     my ($symb)=&get_symb($r);
1.75      albertel 4641:     if (!$symb) {return '';}
1.423     albertel 4642:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4643:     my $default_form_data=&defaultFormData($symb);
                   4644:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4645:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4646:     my $format_selector=&scantron_scantab();
1.186     albertel 4647:     my $CODE_selector=&scantron_CODElist();
                   4648:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4649:     my $result;
1.422     foxr     4650: 
                   4651:     # Chunk of form to prompt for a file to grade and how:
                   4652: 
1.75      albertel 4653:     $result.= <<SCANTRONFORM;
1.162     albertel 4654:     <table width="100%" border="0">
1.75      albertel 4655:     <tr>
1.226     albertel 4656:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4657:       <td bgcolor="#777777">
1.203     albertel 4658:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4659:         $default_form_data
1.75      albertel 4660:         <table width="100%" border="0">
                   4661:           <tr bgcolor="#e6ffff">
1.174     albertel 4662:             <td colspan="2">
                   4663:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4664:             </td>
                   4665:           </tr>
                   4666:           <tr bgcolor="#ffffe6">
1.174     albertel 4667:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4668:           </tr>
                   4669:           <tr bgcolor="#ffffe6">
1.174     albertel 4670:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4671:           </tr>
1.82      albertel 4672:           <tr bgcolor="#ffffe6">
1.174     albertel 4673:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4674:           </tr>
1.157     albertel 4675:           <tr bgcolor="#ffffe6">
1.186     albertel 4676:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4677:           </tr>
                   4678:           <tr bgcolor="#ffffe6">
                   4679:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4680:           </tr>
                   4681:           <tr bgcolor="#ffffe6">
1.187     albertel 4682: 	    <td> Options: </td>
                   4683:             <td>
1.272     albertel 4684: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4685:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4686:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4687: 	    </td>
                   4688:           </tr>
                   4689:           <tr bgcolor="#ffffe6">
1.174     albertel 4690:             <td colspan="2">
1.265     www      4691:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4692:             </td>
                   4693:           </tr>
                   4694:         </table>
1.226     albertel 4695:        </td>
                   4696:      </form>
1.162     albertel 4697:     </tr>
                   4698: SCANTRONFORM
                   4699:    
                   4700:     $r->print($result);
                   4701: 
1.257     albertel 4702:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4703:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4704: 
1.422     foxr     4705: 	# Chunk of form to prompt for a scantron file upload.
                   4706: 
1.162     albertel 4707:         $r->print(<<SCANTRONFORM);
                   4708:     <tr>
                   4709:       <td bgcolor="#777777">
                   4710:         <table width="100%" border="0">
                   4711:           <tr bgcolor="#e6ffff">
                   4712:             <td>
1.174     albertel 4713:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4714:             </td>
                   4715:           </tr>
                   4716:           <tr bgcolor="#ffffe6">
                   4717:             <td>
                   4718: SCANTRONFORM
1.324     albertel 4719:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4720:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4721:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4722:     $r->print(<<UPLOAD);
                   4723:               <script type="text/javascript" language="javascript">
                   4724:     function checkUpload(formname) {
                   4725: 	if (formname.upfile.value == "") {
                   4726: 	    alert("Please use the browse button to select a file from your local directory.");
                   4727: 	    return false;
                   4728: 	}
                   4729: 	formname.submit();
                   4730:     }
                   4731:               </script>
                   4732: 
                   4733:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4734:                 $default_form_data
                   4735:                 <input name='courseid' type='hidden' value='$cnum' />
                   4736:                 <input name='domainid' type='hidden' value='$cdom' />
                   4737:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4738:                 File to upload:<input type="file" name="upfile" size="50" />
                   4739:                 <br />
                   4740:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4741:               </form>
                   4742: UPLOAD
1.162     albertel 4743: 
                   4744:         $r->print(<<SCANTRONFORM);
                   4745:             </td>
                   4746:           </tr>
1.75      albertel 4747:         </table>
                   4748:       </td>
                   4749:     </tr>
1.162     albertel 4750: SCANTRONFORM
                   4751:     }
1.422     foxr     4752: 
                   4753:     # Chunk of the form that prompts to view a scoring office file,
                   4754:     # corrected file, skipped records in a file.
                   4755: 
1.187     albertel 4756:     $r->print(<<SCANTRONFORM);
                   4757:     <tr>
1.226     albertel 4758:       <form action='/adm/grades' name='scantron_download'>
                   4759:         <td bgcolor="#777777">
1.379     albertel 4760: 	  $default_form_data
1.187     albertel 4761:           <input type="hidden" name="command" value="scantron_download" />
                   4762:           <table width="100%" border="0">
                   4763:             <tr bgcolor="#e6ffff">
                   4764:               <td colspan="2">
                   4765:                 &nbsp;<b>Download a scoring office file</b>
                   4766:               </td>
                   4767:             </tr>
                   4768:             <tr bgcolor="#ffffe6">
                   4769:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4770:             </tr>
                   4771:             <tr bgcolor="#ffffe6">
                   4772:               <td colspan="2">
1.293     www      4773:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4774:               </td>
                   4775:             </tr>
                   4776:           </table>
1.226     albertel 4777:         </td>
                   4778:       </form>
1.187     albertel 4779:     </tr>
                   4780: SCANTRONFORM
1.162     albertel 4781: 
                   4782:     $r->print(<<SCANTRONFORM);
1.75      albertel 4783:   </table>
1.81      albertel 4784: $grading_menu_button
1.75      albertel 4785: SCANTRONFORM
                   4786: 
1.162     albertel 4787:     return
1.75      albertel 4788: }
                   4789: 
1.423     albertel 4790: =pod
                   4791: 
                   4792: =item get_scantron_config
                   4793: 
                   4794:    Parse and return the scantron configuration line selected as a
                   4795:    hash of configuration file fields.
                   4796: 
                   4797:  Arguments:
                   4798:     which - the name of the configuration to parse from the file.
                   4799: 
                   4800: 
                   4801:  Returns:
                   4802:             If the named configuration is not in the file, an empty
                   4803:             hash is returned.
                   4804:     a hash with the fields
                   4805:       name         - internal name for the this configuration setup
                   4806:       description  - text to display to operator that describes this config
                   4807:       CODElocation - if 0 or the string 'none'
                   4808:                           - no CODE exists for this config
                   4809:                      if -1 || the string 'letter'
                   4810:                           - a CODE exists for this config and is
                   4811:                             a string of letters
                   4812:                      Unsupported value (but planned for future support)
                   4813:                           if a positive integer
                   4814:                                - The CODE exists as the first n items from
                   4815:                                  the question section of the form
                   4816:                           if the string 'number'
                   4817:                                - The CODE exists for this config and is
                   4818:                                  a string of numbers
                   4819:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4820:                      the CODE starts
                   4821:       CODElength  - length of the CODE
                   4822:       IDstart     - column where the student ID number starts
                   4823:       IDlength    - length of the student ID info
                   4824:       Qstart      - column where the information from the bubbled
                   4825:                     'questions' start
                   4826:       Qlength     - number of columns comprising a single bubble line from
                   4827:                     the sheet. (usually either 1 or 10)
1.424     albertel 4828:       Qon         - either a single character representing the character used
1.423     albertel 4829:                     to signal a bubble was chosen in the positional setup, or
                   4830:                     the string 'letter' if the letter of the chosen bubble is
                   4831:                     in the final, or 'number' if a number representing the
                   4832:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 4833:       Qoff        - the character used to represent that a bubble was
                   4834:                     left blank
1.423     albertel 4835:       PaperID     - if the scanning process generates a unique number for each
                   4836:                     sheet scanned the column that this ID number starts in
                   4837:       PaperIDlength - number of columns that comprise the unique ID number
                   4838:                       for the sheet of paper
1.424     albertel 4839:       FirstName   - column that the first name starts in
1.423     albertel 4840:       FirstNameLength - number of columns that the first name spans
                   4841:  
                   4842:       LastName    - column that the last name starts in
                   4843:       LastNameLength - number of columns that the last name spans
                   4844: 
                   4845: =cut
1.422     foxr     4846: 
1.82      albertel 4847: sub get_scantron_config {
                   4848:     my ($which) = @_;
                   4849:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4850:     my %config;
1.157     albertel 4851:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4852:     foreach my $line (<$fh>) {
                   4853: 	my ($name,$descrip)=split(/:/,$line);
                   4854: 	if ($name ne $which ) { next; }
                   4855: 	chomp($line);
                   4856: 	my @config=split(/:/,$line);
                   4857: 	$config{'name'}=$config[0];
                   4858: 	$config{'description'}=$config[1];
                   4859: 	$config{'CODElocation'}=$config[2];
                   4860: 	$config{'CODEstart'}=$config[3];
                   4861: 	$config{'CODElength'}=$config[4];
                   4862: 	$config{'IDstart'}=$config[5];
                   4863: 	$config{'IDlength'}=$config[6];
                   4864: 	$config{'Qstart'}=$config[7];
                   4865: 	$config{'Qlength'}=$config[8];
                   4866: 	$config{'Qoff'}=$config[9];
                   4867: 	$config{'Qon'}=$config[10];
1.157     albertel 4868: 	$config{'PaperID'}=$config[11];
                   4869: 	$config{'PaperIDlength'}=$config[12];
                   4870: 	$config{'FirstName'}=$config[13];
                   4871: 	$config{'FirstNamelength'}=$config[14];
                   4872: 	$config{'LastName'}=$config[15];
                   4873: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4874: 	last;
                   4875:     }
                   4876:     return %config;
                   4877: }
                   4878: 
1.423     albertel 4879: =pod 
                   4880: 
                   4881: =item username_to_idmap
                   4882: 
                   4883:     creates a hash keyed by student id with values of the corresponding
                   4884:     student username:domain.
                   4885: 
                   4886:   Arguments:
                   4887: 
                   4888:     $classlist - reference to the class list hash. This is a hash
                   4889:                  keyed by student name:domain  whose elements are references
1.424     albertel 4890:                  to arrays containing various chunks of information
1.423     albertel 4891:                  about the student. (See loncoursedata for more info).
                   4892: 
                   4893:   Returns
                   4894:     %idmap - the constructed hash
                   4895: 
                   4896: =cut
                   4897: 
1.82      albertel 4898: sub username_to_idmap {
                   4899:     my ($classlist)= @_;
                   4900:     my %idmap;
                   4901:     foreach my $student (keys(%$classlist)) {
                   4902: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4903: 	    $student;
                   4904:     }
                   4905:     return %idmap;
                   4906: }
1.423     albertel 4907: 
                   4908: =pod
                   4909: 
1.424     albertel 4910: =item scantron_fixup_scanline
1.423     albertel 4911: 
                   4912:    Process a requested correction to a scanline.
                   4913: 
                   4914:   Arguments:
                   4915:     $scantron_config   - hash from &get_scantron_config()
                   4916:     $scan_data         - hash of correction information 
                   4917:                           (see &scantron_getfile())
                   4918:     $line              - existing scanline
                   4919:     $whichline         - line number of the passed in scanline
                   4920:     $field             - type of change to process 
                   4921:                          (either 
                   4922:                           'ID'     -> correct the student ID number
                   4923:                           'CODE'   -> correct the CODE
                   4924:                           'answer' -> fixup the submitted answers)
                   4925:     
                   4926:    $args               - hash of additional info,
                   4927:                           - 'ID' 
                   4928:                                'newid' -> studentID to use in replacement
1.424     albertel 4929:                                           of existing one
1.423     albertel 4930:                           - 'CODE' 
                   4931:                                'CODE_ignore_dup' - set to true if duplicates
                   4932:                                                    should be ignored.
                   4933: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 4934:                                         if the existing unfound code should
1.423     albertel 4935:                                         be used as is
                   4936:                           - 'answer'
                   4937:                                'response' - new answer or 'none' if blank
                   4938:                                'question' - the bubble line to change
                   4939: 
                   4940:   Returns:
                   4941:     $line - the modified scanline
                   4942: 
                   4943:   Side effects: 
                   4944:     $scan_data - may be updated
                   4945: 
                   4946: =cut
                   4947: 
1.82      albertel 4948: 
1.157     albertel 4949: sub scantron_fixup_scanline {
                   4950:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.423     albertel 4951: 
1.157     albertel 4952:     if ($field eq 'ID') {
                   4953: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 4954: 	    return ($line,1,'New value too large');
1.157     albertel 4955: 	}
                   4956: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   4957: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   4958: 				     $args->{'newid'});
                   4959: 	}
                   4960: 	substr($line,$$scantron_config{'IDstart'}-1,
                   4961: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   4962: 	if ($args->{'newid'}=~/^\s*$/) {
                   4963: 	    &scan_data($scan_data,"$whichline.user",
                   4964: 		       $args->{'username'}.':'.$args->{'domain'});
                   4965: 	}
1.186     albertel 4966:     } elsif ($field eq 'CODE') {
1.192     albertel 4967: 	if ($args->{'CODE_ignore_dup'}) {
                   4968: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   4969: 	}
                   4970: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   4971: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 4972: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   4973: 		return ($line,1,'New CODE value too large');
                   4974: 	    }
                   4975: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   4976: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   4977: 	    }
                   4978: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   4979: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 4980: 	}
1.157     albertel 4981:     } elsif ($field eq 'answer') {
                   4982: 	my $length=$scantron_config->{'Qlength'};
                   4983: 	my $off=$scantron_config->{'Qoff'};
                   4984: 	my $on=$scantron_config->{'Qon'};
                   4985: 	my $answer=${off}x$length;
                   4986: 	if ($args->{'response'} eq 'none') {
                   4987: 	    &scan_data($scan_data,
                   4988: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   4989: 	} else {
1.274     albertel 4990: 	    if ($on eq 'letter') {
                   4991: 		my @alphabet=('A'..'Z');
                   4992: 		$answer=$alphabet[$args->{'response'}];
                   4993: 	    } elsif ($on eq 'number') {
                   4994: 		$answer=$args->{'response'}+1;
1.389     albertel 4995: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 4996: 	    } else {
                   4997: 		substr($answer,$args->{'response'},1)=$on;
                   4998: 	    }
1.157     albertel 4999: 	    &scan_data($scan_data,
                   5000: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   5001: 	}
                   5002: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5003: 	substr($line,$where-1,$length)=$answer;
                   5004:     }
                   5005:     return $line;
                   5006: }
1.423     albertel 5007: 
                   5008: =pod
                   5009: 
                   5010: =item scan_data
                   5011: 
                   5012:     Edit or look up  an item in the scan_data hash.
                   5013: 
                   5014:   Arguments:
                   5015:     $scan_data  - The hash (see scantron_getfile)
                   5016:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5017:                   scantronfilename_key).
1.423     albertel 5018:     $data        - New value of the hash entry.
                   5019:     $delete      - If true, the entry is removed from the hash.
                   5020: 
                   5021:   Returns:
                   5022:     The new value of the hash table field (undefined if deleted).
                   5023: 
                   5024: =cut
                   5025: 
                   5026: 
1.157     albertel 5027: sub scan_data {
                   5028:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5029:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5030:     if (defined($value)) {
                   5031: 	$scan_data->{$filename.'_'.$key} = $value;
                   5032:     }
                   5033:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5034:     return $scan_data->{$filename.'_'.$key};
                   5035: }
1.423     albertel 5036: 
                   5037: =pod 
                   5038: 
                   5039: =item scantron_parse_scanline
                   5040: 
                   5041:   Decodes a scanline from the selected scantron file
                   5042: 
                   5043:  Arguments:
                   5044:     line             - The text of the scantron file line to process
                   5045:     whichline        - Line number
                   5046:     scantron_config  - Hash describing the format of the scantron lines.
                   5047:     scan_data        - Hash of extra information about the scanline
                   5048:                        (see scantron_getfile for more information)
                   5049:     just_header      - True if should not process question answers but only
                   5050:                        the stuff to the left of the answers.
                   5051:  Returns:
                   5052:    Hash containing the result of parsing the scanline
                   5053: 
                   5054:    Keys are all proceeded by the string 'scantron.'
                   5055: 
                   5056:        CODE    - the CODE in use for this scanline
                   5057:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5058:                  by the operator
                   5059:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5060:                             CODEs were selected, but the usage has been
                   5061:                             forced by the operator
                   5062:        ID  - student ID
                   5063:        PaperID - if used, the ID number printed on the sheet when the 
                   5064:                  paper was scanned
                   5065:        FirstName - first name from the sheet
                   5066:        LastName  - last name from the sheet
                   5067: 
                   5068:      if just_header was not true these key may also exist
                   5069: 
                   5070:        missingerror - a list of bubbled line numbers that had a blank bubble
                   5071:                       that is considered an error (if the operator had already
                   5072:                       okayed a blank bubble line as really being blank then
                   5073:                       that bubble line number won't appear here.
                   5074:        doubleerror  - a list of bubbled line numbers that had more than one
                   5075:                       bubble filled in and has not been corrected by the
                   5076:                       operator
                   5077:        maxquest     - the number of the last bubble line that was parsed
                   5078: 
                   5079:        (<number> starts at 1)
                   5080:        <number>.answer - zero or more letters representing the selected
                   5081:                          letters from the scanline for the bubble line 
                   5082:                          <number>.
                   5083:                          if blank there was either no bubble or there where
                   5084:                          multiple bubbles, (consult the keys missingerror and
                   5085:                          doubleerror if this is an error condition)
                   5086: 
                   5087: =cut
                   5088: 
1.82      albertel 5089: sub scantron_parse_scanline {
1.423     albertel 5090:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.82      albertel 5091:     my %record;
1.422     foxr     5092:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5093:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5094:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5095: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5096: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5097: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5098: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5099: 	    $record{'scantron.CODE'}=substr($data,
                   5100: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5101: 					    $$scantron_config{'CODElength'});
1.191     albertel 5102: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5103: 		$record{'scantron.useCODE'}=1;
                   5104: 	    }
1.192     albertel 5105: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5106: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5107: 	    }
1.82      albertel 5108: 	} else {
                   5109: 	    #FIXME interpret first N questions
                   5110: 	}
                   5111:     }
1.83      albertel 5112:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5113: 				  $$scantron_config{'IDlength'});
1.157     albertel 5114:     $record{'scantron.PaperID'}=
                   5115: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5116: 	       $$scantron_config{'PaperIDlength'});
                   5117:     $record{'scantron.FirstName'}=
                   5118: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5119: 	       $$scantron_config{'FirstNamelength'});
                   5120:     $record{'scantron.LastName'}=
                   5121: 	substr($data,$$scantron_config{'LastName'}-1,
                   5122: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5123:     if ($just_header) { return \%record; }
1.194     albertel 5124: 
1.82      albertel 5125:     my @alphabet=('A'..'Z');
                   5126:     my $questnum=0;
                   5127:     while ($questions) {
                   5128: 	$questnum++;
                   5129: 	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
                   5130: 	substr($questions,0,$$scantron_config{'Qlength'})='';
1.83      albertel 5131: 	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
1.239     albertel 5132: 	if ($$scantron_config{'Qon'} eq 'letter') {
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)
1.274     albertel 5138: 		     || $currentquest eq $$scantron_config{'Qoff'}
                   5139: 		     || $currentquest !~ /^[A-Z]$/) {
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 {
                   5145: 		$record{"scantron.$questnum.answer"}=$currentquest;
                   5146: 	    }
                   5147: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.371     albertel 5148: 	    if ($currentquest eq '?'
                   5149: 		|| $currentquest eq '*') {
1.274     albertel 5150: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5151: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 5152: 	    } elsif (!defined($currentquest)
                   5153: 		     || $currentquest eq $$scantron_config{'Qoff'} 
                   5154: 		     || $currentquest !~ /^\d$/) {
1.239     albertel 5155: 		$record{"scantron.$questnum.answer"}='';
                   5156: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5157: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5158: 		}
                   5159: 	    } else {
1.371     albertel 5160: 		# wrap zero back to J
                   5161: 		if ($currentquest eq '0') {
                   5162: 		    $record{"scantron.$questnum.answer"}=
                   5163: 			$alphabet[9];
                   5164: 		} else {
                   5165: 		    $record{"scantron.$questnum.answer"}=
                   5166: 			$alphabet[$currentquest-1];
                   5167: 		}
1.239     albertel 5168: 	    }
1.82      albertel 5169: 	} else {
1.239     albertel 5170: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
                   5171: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}) {
                   5172: 		$record{"scantron.$questnum.answer"}='';
                   5173: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5174: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5175: 		}
                   5176: 	    } else {
                   5177: 		$record{"scantron.$questnum.answer"}=
                   5178: 		    $alphabet[length($array[0])];
                   5179: 	    }
                   5180: 	    if (scalar(@array) gt 2) {
                   5181: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5182: 		my @ans=@array;
                   5183: 		my $i=length($ans[0]);shift(@ans);
                   5184: 		while ($#ans) {
                   5185: 		    $i+=length($ans[0])+1;
                   5186: 		    $record{"scantron.$questnum.answer"}.=$alphabet[$i];
                   5187: 		    shift(@ans);
                   5188: 		}
                   5189: 	    }
1.82      albertel 5190: 	}
                   5191:     }
1.83      albertel 5192:     $record{'scantron.maxquest'}=$questnum;
                   5193:     return \%record;
1.82      albertel 5194: }
                   5195: 
1.423     albertel 5196: =pod
                   5197: 
                   5198: =item scantron_add_delay
                   5199: 
                   5200:    Adds an error message that occurred during the grading phase to a
                   5201:    queue of messages to be shown after grading pass is complete
                   5202: 
                   5203:  Arguments:
1.424     albertel 5204:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5205:    $scanline    - the scanline that caused the error
                   5206:    $errormesage - the error message
                   5207:    $errorcode   - a numeric code for the error
                   5208: 
                   5209:  Side Effects:
1.424     albertel 5210:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5211: 
                   5212: =cut
                   5213: 
1.82      albertel 5214: sub scantron_add_delay {
1.140     albertel 5215:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5216:     push(@$delayqueue,
                   5217: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5218: 	  'ecode' => $errorcode }
                   5219: 	 );
1.82      albertel 5220: }
                   5221: 
1.423     albertel 5222: =pod
                   5223: 
                   5224: =item scantron_find_student
                   5225: 
1.424     albertel 5226:    Finds the username for the current scanline
                   5227: 
                   5228:   Arguments:
                   5229:    $scantron_record - hash result from scantron_parse_scanline
                   5230:    $scan_data       - hash of correction information 
                   5231:                       (see &scantron_getfile() form more information)
                   5232:    $idmap           - hash from &username_to_idmap()
                   5233:    $line            - number of current scanline
                   5234:  
                   5235:   Returns:
                   5236:    Either 'username:domain' or undef if unknown
                   5237: 
1.423     albertel 5238: =cut
                   5239: 
1.82      albertel 5240: sub scantron_find_student {
1.157     albertel 5241:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5242:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5243:     if ($scanID =~ /^\s*$/) {
                   5244:  	return &scan_data($scan_data,"$line.user");
                   5245:     }
1.83      albertel 5246:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5247:  	if (lc($id) eq lc($scanID)) {
                   5248:  	    return $$idmap{$id};
                   5249:  	}
1.83      albertel 5250:     }
                   5251:     return undef;
                   5252: }
                   5253: 
1.423     albertel 5254: =pod
                   5255: 
                   5256: =item scantron_filter
                   5257: 
1.424     albertel 5258:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5259:    hidden resources was selected
                   5260: 
1.423     albertel 5261: =cut
                   5262: 
1.83      albertel 5263: sub scantron_filter {
                   5264:     my ($curres)=@_;
1.331     albertel 5265: 
                   5266:     if (ref($curres) && $curres->is_problem()) {
                   5267: 	# if the user has asked to not have either hidden
                   5268: 	# or 'randomout' controlled resources to be graded
                   5269: 	# don't include them
                   5270: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5271: 	    && $curres->randomout) {
                   5272: 	    return 0;
                   5273: 	}
1.83      albertel 5274: 	return 1;
                   5275:     }
                   5276:     return 0;
1.82      albertel 5277: }
                   5278: 
1.423     albertel 5279: =pod
                   5280: 
                   5281: =item scantron_process_corrections
                   5282: 
1.424     albertel 5283:    Gets correction information out of submitted form data and corrects
                   5284:    the scanline
                   5285: 
1.423     albertel 5286: =cut
                   5287: 
1.157     albertel 5288: sub scantron_process_corrections {
                   5289:     my ($r) = @_;
1.257     albertel 5290:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5291:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5292:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5293:     my $which=$env{'form.scantron_line'};
1.200     albertel 5294:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5295:     my ($skip,$err,$errmsg);
1.257     albertel 5296:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5297: 	$skip=1;
1.257     albertel 5298:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5299: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5300: 	    $env{'form.scantron_domain'};
1.157     albertel 5301: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5302: 	($line,$err,$errmsg)=
                   5303: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5304: 				     'ID',{'newid'=>$newid,
1.257     albertel 5305: 				    'username'=>$env{'form.scantron_username'},
                   5306: 				    'domain'=>$env{'form.scantron_domain'}});
                   5307:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5308: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5309: 	my $newCODE;
1.192     albertel 5310: 	my %args;
1.190     albertel 5311: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5312: 	    $newCODE='use_unfound';
1.190     albertel 5313: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5314: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5315: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5316: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5317: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5318: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5319: 	}
1.257     albertel 5320: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5321: 	    $args{'CODE_ignore_dup'}=1;
                   5322: 	}
                   5323: 	$args{'CODE'}=$newCODE;
1.186     albertel 5324: 	($line,$err,$errmsg)=
                   5325: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5326: 				     'CODE',\%args);
1.257     albertel 5327:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5328: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5329: 	    ($line,$err,$errmsg)=
                   5330: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5331: 					 $which,'answer',
                   5332: 					 { 'question'=>$question,
1.257     albertel 5333: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5334: 	    if ($err) { last; }
                   5335: 	}
                   5336:     }
                   5337:     if ($err) {
1.398     albertel 5338: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5339:     } else {
1.200     albertel 5340: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5341: 	&scantron_putfile($scanlines,$scan_data);
                   5342:     }
                   5343: }
                   5344: 
1.423     albertel 5345: =pod
                   5346: 
                   5347: =item reset_skipping_status
                   5348: 
1.424     albertel 5349:    Forgets the current set of remember skipped scanlines (and thus
                   5350:    reverts back to considering all lines in the
                   5351:    scantron_skipped_<filename> file)
                   5352: 
1.423     albertel 5353: =cut
                   5354: 
1.200     albertel 5355: sub reset_skipping_status {
                   5356:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5357:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5358:     &scantron_putfile(undef,$scan_data);
                   5359: }
                   5360: 
1.423     albertel 5361: =pod
                   5362: 
                   5363: =item start_skipping
                   5364: 
1.424     albertel 5365:    Marks a scanline to be skipped. 
                   5366: 
1.423     albertel 5367: =cut
                   5368: 
1.376     albertel 5369: sub start_skipping {
1.200     albertel 5370:     my ($scan_data,$i)=@_;
                   5371:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5372:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5373: 	$remembered{$i}=2;
                   5374:     } else {
                   5375: 	$remembered{$i}=1;
                   5376:     }
1.200     albertel 5377:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5378: }
                   5379: 
1.423     albertel 5380: =pod
                   5381: 
                   5382: =item should_be_skipped
                   5383: 
1.424     albertel 5384:    Checks whether a scanline should be skipped.
                   5385: 
1.423     albertel 5386: =cut
                   5387: 
1.200     albertel 5388: sub should_be_skipped {
1.376     albertel 5389:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5390:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5391: 	# not redoing old skips
1.376     albertel 5392: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5393: 	return 0;
                   5394:     }
                   5395:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5396: 
                   5397:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5398: 	return 0;
                   5399:     }
1.200     albertel 5400:     return 1;
                   5401: }
                   5402: 
1.423     albertel 5403: =pod
                   5404: 
                   5405: =item remember_current_skipped
                   5406: 
1.424     albertel 5407:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5408:    file and remembers them into scan_data for later use.
                   5409: 
1.423     albertel 5410: =cut
                   5411: 
1.200     albertel 5412: sub remember_current_skipped {
                   5413:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5414:     my %to_remember;
                   5415:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5416: 	if ($scanlines->{'skipped'}[$i]) {
                   5417: 	    $to_remember{$i}=1;
                   5418: 	}
                   5419:     }
1.376     albertel 5420: 
1.200     albertel 5421:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5422:     &scantron_putfile(undef,$scan_data);
                   5423: }
                   5424: 
1.423     albertel 5425: =pod
                   5426: 
                   5427: =item check_for_error
                   5428: 
1.424     albertel 5429:     Checks if there was an error when attempting to remove a specific
                   5430:     scantron_.. bubble sheet data file. Prints out an error if
                   5431:     something went wrong.
                   5432: 
1.423     albertel 5433: =cut
                   5434: 
1.200     albertel 5435: sub check_for_error {
                   5436:     my ($r,$result)=@_;
                   5437:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5438: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5439:     }
                   5440: }
1.157     albertel 5441: 
1.423     albertel 5442: =pod
                   5443: 
                   5444: =item scantron_warning_screen
                   5445: 
1.424     albertel 5446:    Interstitial screen to make sure the operator has selected the
                   5447:    correct options before we start the validation phase.
                   5448: 
1.423     albertel 5449: =cut
                   5450: 
1.203     albertel 5451: sub scantron_warning_screen {
                   5452:     my ($button_text)=@_;
1.257     albertel 5453:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5454:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5455:     my $CODElist;
1.284     albertel 5456:     if ($scantron_config{'CODElocation'} &&
                   5457: 	$scantron_config{'CODEstart'} &&
                   5458: 	$scantron_config{'CODElength'}) {
                   5459: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5460: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5461: 	$CODElist=
                   5462: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5463: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5464:     }
1.203     albertel 5465:     return (<<STUFF);
                   5466: <p>
1.398     albertel 5467: <span class="LC_warning">Please double check the information
                   5468:                  below before clicking on '$button_text'</span>
1.203     albertel 5469: </p>
                   5470: <table>
1.284     albertel 5471: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5472: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5473: $CODElist
1.203     albertel 5474: </table>
                   5475: <br />
                   5476: <p> If this information is correct, please click on '$button_text'.</p>
                   5477: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5478: 
                   5479: <br />
                   5480: STUFF
                   5481: }
                   5482: 
1.423     albertel 5483: =pod
                   5484: 
                   5485: =item scantron_do_warning
                   5486: 
1.424     albertel 5487:    Check if the operator has picked something for all required
                   5488:    fields. Error out if something is missing.
                   5489: 
1.423     albertel 5490: =cut
                   5491: 
1.203     albertel 5492: sub scantron_do_warning {
                   5493:     my ($r)=@_;
1.324     albertel 5494:     my ($symb)=&get_symb($r);
1.203     albertel 5495:     if (!$symb) {return '';}
1.324     albertel 5496:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5497:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5498:     if ( $env{'form.selectpage'} eq '' ||
                   5499: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5500: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5501: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5502: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5503: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5504: 	} 
1.257     albertel 5505: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5506: 	    $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 5507: 	} 
1.257     albertel 5508: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5509: 	    $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 5510: 	} 
                   5511:     } else {
1.265     www      5512: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5513: 	$r->print(<<STUFF);
1.203     albertel 5514: $warning
1.265     www      5515: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5516: <input type="hidden" name="command" value="scantron_validate" />
                   5517: STUFF
1.237     albertel 5518:     }
1.352     albertel 5519:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5520:     return '';
                   5521: }
                   5522: 
1.423     albertel 5523: =pod
                   5524: 
                   5525: =item scantron_form_start
                   5526: 
1.424     albertel 5527:     html hidden input for remembering all selected grading options
                   5528: 
1.423     albertel 5529: =cut
                   5530: 
1.203     albertel 5531: sub scantron_form_start {
                   5532:     my ($max_bubble)=@_;
                   5533:     my $result= <<SCANTRONFORM;
                   5534: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5535:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5536:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5537:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5538:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5539:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5540:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5541:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5542:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5543:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5544: SCANTRONFORM
                   5545:     return $result;
                   5546: }
                   5547: 
1.423     albertel 5548: =pod
                   5549: 
                   5550: =item scantron_validate_file
                   5551: 
1.424     albertel 5552:     Dispatch routine for doing validation of a bubble sheet data file.
                   5553: 
                   5554:     Also processes any necessary information resets that need to
                   5555:     occur before validation begins (ignore previous corrections,
                   5556:     restarting the skipped records processing)
                   5557: 
1.423     albertel 5558: =cut
                   5559: 
1.157     albertel 5560: sub scantron_validate_file {
                   5561:     my ($r) = @_;
1.324     albertel 5562:     my ($symb)=&get_symb($r);
1.157     albertel 5563:     if (!$symb) {return '';}
1.324     albertel 5564:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5565:     
                   5566:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5567:     # them when doing the corrections reset
1.257     albertel 5568:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5569: 	&reset_skipping_status();
                   5570:     }
1.257     albertel 5571:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5572: 	&remember_current_skipped();
1.257     albertel 5573: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5574:     }
                   5575: 
1.257     albertel 5576:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5577: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5578: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5579: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5580: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5581:     }
1.200     albertel 5582: 
1.257     albertel 5583:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5584: 	&scantron_process_corrections($r);
                   5585:     }
1.424     albertel 5586:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5587:     #get the student pick code ready
                   5588:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5589:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5590:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5591:     $r->print($result);
                   5592:     
1.334     albertel 5593:     my @validate_phases=( 'sequence',
                   5594: 			  'ID',
1.157     albertel 5595: 			  'CODE',
                   5596: 			  'doublebubble',
                   5597: 			  'missingbubbles');
1.257     albertel 5598:     if (!$env{'form.validatepass'}) {
                   5599: 	$env{'form.validatepass'} = 0;
1.157     albertel 5600:     }
1.257     albertel 5601:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5602: 
                   5603:     my $stop=0;
                   5604:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5605: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5606: 	$r->rflush();
                   5607: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5608: 	{
                   5609: 	    no strict 'refs';
                   5610: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5611: 	}
                   5612:     }
                   5613:     if (!$stop) {
1.203     albertel 5614: 	my $warning=&scantron_warning_screen('Start Grading');
                   5615: 	$r->print(<<STUFF);
                   5616: Validation process complete.<br />
                   5617: $warning
                   5618: <input type="submit" name="submit" value="Start Grading" />
                   5619: <input type="hidden" name="command" value="scantron_process" />
                   5620: STUFF
                   5621: 
1.157     albertel 5622:     } else {
                   5623: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5624: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5625:     }
                   5626:     if ($stop) {
1.334     albertel 5627: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5628: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5629: 	    $r->print(' this error <br />');
                   5630: 
                   5631: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5632: 	} else {
                   5633: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5634: 	    $r->print(' using corrected info <br />');
                   5635: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5636: 	    $r->print(" this scanline saving it for later.");
                   5637: 	}
1.157     albertel 5638:     }
1.352     albertel 5639:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5640:     return '';
                   5641: }
                   5642: 
1.423     albertel 5643: 
                   5644: =pod
                   5645: 
                   5646: =item scantron_remove_file
                   5647: 
1.424     albertel 5648:    Removes the requested bubble sheet data file, makes sure that
                   5649:    scantron_original_<filename> is never removed
                   5650: 
                   5651: 
1.423     albertel 5652: =cut
                   5653: 
1.200     albertel 5654: sub scantron_remove_file {
1.192     albertel 5655:     my ($which)=@_;
1.257     albertel 5656:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5657:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5658:     my $file='scantron_';
1.200     albertel 5659:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5660: 	$file.=$which.'_';
1.192     albertel 5661:     } else {
                   5662: 	return 'refused';
                   5663:     }
1.257     albertel 5664:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5665:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5666: }
                   5667: 
1.423     albertel 5668: 
                   5669: =pod
                   5670: 
                   5671: =item scantron_remove_scan_data
                   5672: 
1.424     albertel 5673:    Removes all scan_data correction for the requested bubble sheet
                   5674:    data file.  (In the case that both the are doing skipped records we need
                   5675:    to remember the old skipped lines for the time being so that element
                   5676:    persists for a while.)
                   5677: 
1.423     albertel 5678: =cut
                   5679: 
1.200     albertel 5680: sub scantron_remove_scan_data {
1.257     albertel 5681:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5682:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5683:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5684:     my @todelete;
1.257     albertel 5685:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5686:     foreach my $key (@keys) {
                   5687: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5688: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5689: 		$key=~/remember_skipping/) {
                   5690: 		next;
                   5691: 	    }
1.192     albertel 5692: 	    push(@todelete,$key);
                   5693: 	}
                   5694:     }
1.200     albertel 5695:     my $result;
1.192     albertel 5696:     if (@todelete) {
1.200     albertel 5697: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5698:     }
                   5699:     return $result;
                   5700: }
                   5701: 
1.423     albertel 5702: 
                   5703: =pod
                   5704: 
                   5705: =item scantron_getfile
                   5706: 
1.424     albertel 5707:     Fetches the requested bubble sheet data file (all 3 versions), and
                   5708:     the scan_data hash
                   5709:   
                   5710:   Arguments:
                   5711:     None
                   5712: 
                   5713:   Returns:
                   5714:     2 hash references
                   5715: 
                   5716:      - first one has 
                   5717:          orig      -
                   5718:          corrected -
                   5719:          skipped   -  each of which points to an array ref of the specified
                   5720:                       file broken up into individual lines
                   5721:          count     - number of scanlines
                   5722:  
                   5723:      - second is the scan_data hash possible keys are
1.425     albertel 5724:        ($number refers to scanline numbered $number and thus the key affects
                   5725:         only that scanline
                   5726:         $bubline refers to the specific bubble line element and the aspects
                   5727:         refers to that specific bubble line element)
                   5728: 
                   5729:        $number.user - username:domain to use
                   5730:        $number.CODE_ignore_dup 
                   5731:                     - ignore the duplicate CODE error 
                   5732:        $number.useCODE
                   5733:                     - use the CODE in the scanline as is
                   5734:        $number.no_bubble.$bubline
                   5735:                     - it is valid that there is no bubbled in bubble
                   5736:                       at $number $bubline
                   5737:        remember_skipping
                   5738:                     - a frozen hash containing keys of $number and values
                   5739:                       of either 
                   5740:                         1 - we are on a 'do skipped records pass' and plan
                   5741:                             on processing this line
                   5742:                         2 - we are on a 'do skipped records pass' and this
                   5743:                             scanline has been marked to skip yet again
1.424     albertel 5744: 
1.423     albertel 5745: =cut
                   5746: 
1.157     albertel 5747: sub scantron_getfile {
1.200     albertel 5748:     #FIXME really would prefer a scantron directory
1.257     albertel 5749:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5750:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5751:     my $lines;
                   5752:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5753: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5754:     my %scanlines;
                   5755:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5756:     my $temp=$scanlines{'orig'};
                   5757:     $scanlines{'count'}=$#$temp;
                   5758: 
                   5759:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5760: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5761:     if ($lines eq '-1') {
                   5762: 	$scanlines{'corrected'}=[];
                   5763:     } else {
                   5764: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5765:     }
                   5766:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5767: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5768:     if ($lines eq '-1') {
                   5769: 	$scanlines{'skipped'}=[];
                   5770:     } else {
                   5771: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5772:     }
1.175     albertel 5773:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5774:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5775:     my %scan_data = @tmp;
                   5776:     return (\%scanlines,\%scan_data);
                   5777: }
                   5778: 
1.423     albertel 5779: =pod
                   5780: 
                   5781: =item lonnet_putfile
                   5782: 
1.424     albertel 5783:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   5784: 
                   5785:  Arguments:
                   5786:    $contents - data to store
                   5787:    $filename - filename to store $contents into
                   5788: 
                   5789:  Returns:
                   5790:    result value from &Apache::lonnet::finishuserfileupload
                   5791: 
1.423     albertel 5792: =cut
                   5793: 
1.157     albertel 5794: sub lonnet_putfile {
                   5795:     my ($contents,$filename)=@_;
1.257     albertel 5796:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5797:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5798:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 5799:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 5800: 
                   5801: }
                   5802: 
1.423     albertel 5803: =pod
                   5804: 
                   5805: =item scantron_putfile
                   5806: 
1.424     albertel 5807:     Stores the current version of the bubble sheet data files, and the
                   5808:     scan_data hash. (Does not modify the original version only the
                   5809:     corrected and skipped versions.
                   5810: 
                   5811:  Arguments:
                   5812:     $scanlines - hash ref that looks like the first return value from
                   5813:                  &scantron_getfile()
                   5814:     $scan_data - hash ref that looks like the second return value from
                   5815:                  &scantron_getfile()
                   5816: 
1.423     albertel 5817: =cut
                   5818: 
1.157     albertel 5819: sub scantron_putfile {
                   5820:     my ($scanlines,$scan_data) = @_;
1.200     albertel 5821:     #FIXME really would prefer a scantron directory
1.257     albertel 5822:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5823:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 5824:     if ($scanlines) {
                   5825: 	my $prefix='scantron_';
1.157     albertel 5826: # no need to update orig, shouldn't change
                   5827: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 5828: #		    $env{'form.scantron_selectfile'});
1.200     albertel 5829: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   5830: 			$prefix.'corrected_'.
1.257     albertel 5831: 			$env{'form.scantron_selectfile'});
1.200     albertel 5832: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   5833: 			$prefix.'skipped_'.
1.257     albertel 5834: 			$env{'form.scantron_selectfile'});
1.200     albertel 5835:     }
1.175     albertel 5836:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 5837: }
                   5838: 
1.423     albertel 5839: =pod
                   5840: 
                   5841: =item scantron_get_line
                   5842: 
1.424     albertel 5843:    Returns the correct version of the scanline
                   5844: 
                   5845:  Arguments:
                   5846:     $scanlines - hash ref that looks like the first return value from
                   5847:                  &scantron_getfile()
                   5848:     $scan_data - hash ref that looks like the second return value from
                   5849:                  &scantron_getfile()
                   5850:     $i         - number of the requested line (starts at 0)
                   5851: 
                   5852:  Returns:
                   5853:    A scanline, (either the original or the corrected one if it
                   5854:    exists), or undef if the requested scanline should be
                   5855:    skipped. (Either because it's an skipped scanline, or it's an
                   5856:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   5857:    pass.
                   5858: 
1.423     albertel 5859: =cut
                   5860: 
1.157     albertel 5861: sub scantron_get_line {
1.200     albertel 5862:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 5863:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   5864:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 5865:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   5866:     return $scanlines->{'orig'}[$i]; 
                   5867: }
                   5868: 
1.423     albertel 5869: =pod
                   5870: 
                   5871: =item scantron_todo_count
                   5872: 
1.424     albertel 5873:     Counts the number of scanlines that need processing.
                   5874: 
                   5875:  Arguments:
                   5876:     $scanlines - hash ref that looks like the first return value from
                   5877:                  &scantron_getfile()
                   5878:     $scan_data - hash ref that looks like the second return value from
                   5879:                  &scantron_getfile()
                   5880: 
                   5881:  Returns:
                   5882:     $count - number of scanlines to process
                   5883: 
1.423     albertel 5884: =cut
                   5885: 
1.200     albertel 5886: sub get_todo_count {
                   5887:     my ($scanlines,$scan_data)=@_;
                   5888:     my $count=0;
                   5889:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5890: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   5891: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5892: 	$count++;
                   5893:     }
                   5894:     return $count;
                   5895: }
                   5896: 
1.423     albertel 5897: =pod
                   5898: 
                   5899: =item scantron_put_line
                   5900: 
1.424     albertel 5901:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   5902:     data file.
                   5903: 
                   5904:  Arguments:
                   5905:     $scanlines - hash ref that looks like the first return value from
                   5906:                  &scantron_getfile()
                   5907:     $scan_data - hash ref that looks like the second return value from
                   5908:                  &scantron_getfile()
                   5909:     $i         - line number to update
                   5910:     $newline   - contents of the updated scanline
                   5911:     $skip      - if true make the line for skipping and update the
                   5912:                  'skipped' file
                   5913: 
1.423     albertel 5914: =cut
                   5915: 
1.157     albertel 5916: sub scantron_put_line {
1.200     albertel 5917:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 5918:     if ($skip) {
                   5919: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 5920: 	&start_skipping($scan_data,$i);
1.157     albertel 5921: 	return;
                   5922:     }
                   5923:     $scanlines->{'corrected'}[$i]=$newline;
                   5924: }
                   5925: 
1.423     albertel 5926: =pod
                   5927: 
                   5928: =item scantron_clear_skip
                   5929: 
1.424     albertel 5930:    Remove a line from the 'skipped' file
                   5931: 
                   5932:  Arguments:
                   5933:     $scanlines - hash ref that looks like the first return value from
                   5934:                  &scantron_getfile()
                   5935:     $scan_data - hash ref that looks like the second return value from
                   5936:                  &scantron_getfile()
                   5937:     $i         - line number to update
                   5938: 
1.423     albertel 5939: =cut
                   5940: 
1.376     albertel 5941: sub scantron_clear_skip {
                   5942:     my ($scanlines,$scan_data,$i)=@_;
                   5943:     if (exists($scanlines->{'skipped'}[$i])) {
                   5944: 	undef($scanlines->{'skipped'}[$i]);
                   5945: 	return 1;
                   5946:     }
                   5947:     return 0;
                   5948: }
                   5949: 
1.423     albertel 5950: =pod
                   5951: 
                   5952: =item scantron_filter_not_exam
                   5953: 
1.424     albertel 5954:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   5955:    filter out resources that are not marked as 'exam' mode
                   5956: 
1.423     albertel 5957: =cut
                   5958: 
1.334     albertel 5959: sub scantron_filter_not_exam {
                   5960:     my ($curres)=@_;
                   5961:     
                   5962:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   5963: 	# if the user has asked to not have either hidden
                   5964: 	# or 'randomout' controlled resources to be graded
                   5965: 	# don't include them
                   5966: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5967: 	    && $curres->randomout) {
                   5968: 	    return 0;
                   5969: 	}
                   5970: 	return 1;
                   5971:     }
                   5972:     return 0;
                   5973: }
                   5974: 
1.423     albertel 5975: =pod
                   5976: 
                   5977: =item scantron_validate_sequence
                   5978: 
1.424     albertel 5979:     Validates the selected sequence, checking for resource that are
                   5980:     not set to exam mode.
                   5981: 
1.423     albertel 5982: =cut
                   5983: 
1.334     albertel 5984: sub scantron_validate_sequence {
                   5985:     my ($r,$currentphase) = @_;
                   5986: 
                   5987:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5988:     my (undef,undef,$sequence)=
                   5989: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   5990: 
                   5991:     my $map=$navmap->getResourceByUrl($sequence);
                   5992: 
                   5993:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   5994:                                     value="ignore" />');
                   5995:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   5996: 	my @resources=
                   5997: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   5998: 	if (@resources) {
1.357     banghart 5999: 	    $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 6000: 	    return (1,$currentphase);
                   6001: 	}
                   6002:     }
                   6003: 
                   6004:     return (0,$currentphase+1);
                   6005: }
                   6006: 
1.423     albertel 6007: =pod
                   6008: 
                   6009: =item scantron_validate_ID
                   6010: 
1.424     albertel 6011:    Validates all scanlines in the selected file to not have any
                   6012:    invalid or underspecified student IDs
                   6013: 
1.423     albertel 6014: =cut
                   6015: 
1.157     albertel 6016: sub scantron_validate_ID {
                   6017:     my ($r,$currentphase) = @_;
                   6018:     
                   6019:     #get student info
                   6020:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6021:     my %idmap=&username_to_idmap($classlist);
                   6022: 
                   6023:     #get scantron line setup
1.257     albertel 6024:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6025:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6026: 
                   6027:     my %found=('ids'=>{},'usernames'=>{});
                   6028:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6029: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6030: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6031: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6032: 						 $scan_data);
                   6033: 	my $id=$$scan_record{'scantron.ID'};
                   6034: 	my $found;
                   6035: 	foreach my $checkid (keys(%idmap)) {
                   6036: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6037: 	}
                   6038: 	if ($found) {
                   6039: 	    my $username=$idmap{$found};
                   6040: 	    if ($found{'ids'}{$found}) {
                   6041: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6042: 					 $line,'duplicateID',$found);
1.194     albertel 6043: 		return(1,$currentphase);
1.157     albertel 6044: 	    } elsif ($found{'usernames'}{$username}) {
                   6045: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6046: 					 $line,'duplicateID',$username);
1.194     albertel 6047: 		return(1,$currentphase);
1.157     albertel 6048: 	    }
1.186     albertel 6049: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6050: 	    $found{'ids'}{$found}++;
                   6051: 	    $found{'usernames'}{$username}++;
                   6052: 	} else {
                   6053: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6054: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6055: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6056: 		    &scantron_get_correction($r,$i,$scan_record,
                   6057: 					     \%scantron_config,
                   6058: 					     $line,'duplicateID',$username);
1.194     albertel 6059: 		    return(1,$currentphase);
1.157     albertel 6060: 		} elsif (!defined($username)) {
                   6061: 		    &scantron_get_correction($r,$i,$scan_record,
                   6062: 					     \%scantron_config,
                   6063: 					     $line,'incorrectID');
1.194     albertel 6064: 		    return(1,$currentphase);
1.157     albertel 6065: 		}
                   6066: 		$found{'usernames'}{$username}++;
                   6067: 	    } else {
                   6068: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6069: 					 $line,'incorrectID');
1.194     albertel 6070: 		return(1,$currentphase);
1.157     albertel 6071: 	    }
                   6072: 	}
                   6073:     }
                   6074: 
                   6075:     return (0,$currentphase+1);
                   6076: }
                   6077: 
1.423     albertel 6078: =pod
                   6079: 
                   6080: =item scantron_get_correction
                   6081: 
1.424     albertel 6082:    Builds the interface screen to interact with the operator to fix a
                   6083:    specific error condition in a specific scanline
                   6084: 
                   6085:  Arguments:
                   6086:     $r           - Apache request object
                   6087:     $i           - number of the current scanline
                   6088:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6089:     $scan_config - hash ref as returned from &get_scantron_config()
                   6090:     $line        - full contents of the current scanline
                   6091:     $error       - error condition, valid values are
                   6092:                    'incorrectCODE', 'duplicateCODE',
                   6093:                    'doublebubble', 'missingbubble',
                   6094:                    'duplicateID', 'incorrectID'
                   6095:     $arg         - extra information needed
                   6096:        For errors:
                   6097:          - duplicateID   - paper number that this studentID was seen before on
                   6098:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6099:                            seen on before
                   6100:          - incorrectCODE - current incorrect CODE 
                   6101:          - doublebubble  - array ref of the bubble lines that have double
                   6102:                            bubble errors
                   6103:          - missingbubble - array ref of the bubble lines that have missing
                   6104:                            bubble errors
                   6105: 
1.423     albertel 6106: =cut
                   6107: 
1.157     albertel 6108: sub scantron_get_correction {
                   6109:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6110: 
                   6111: #FIXME in the case of a duplicated ID the previous line, probaly need
                   6112: #to show both the current line and the previous one and allow skipping
                   6113: #the previous one or the current one
                   6114: 
1.161     albertel 6115:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6116:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6117: 	$r->print(" for PaperID <tt>".
                   6118: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6119:     } else {
                   6120: 	$r->print(" in scanline $i <pre>".
                   6121: 		  $line."</pre> \n");
                   6122:     }
1.242     albertel 6123:     my $message="<p>The ID on the form is  <tt>".
                   6124: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6125: 	"The name on the paper is ".
                   6126: 	$$scan_record{'scantron.LastName'}.",".
                   6127: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6128: 
1.157     albertel 6129:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6130:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6131:     if ($error =~ /ID$/) {
1.186     albertel 6132: 	if ($error eq 'incorrectID') {
1.157     albertel 6133: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6134: 	} elsif ($error eq 'duplicateID') {
                   6135: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6136: 	}
1.242     albertel 6137: 	$r->print($message);
1.157     albertel 6138: 	$r->print("<p>How should I handle this? <br /> \n");
                   6139: 	$r->print("\n<ul><li> ");
                   6140: 	#FIXME it would be nice if this sent back the user ID and
                   6141: 	#could do partial userID matches
                   6142: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6143: 				       'scantron_username','scantron_domain'));
                   6144: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6145: 	$r->print("\n@".
1.257     albertel 6146: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6147: 
                   6148: 	$r->print('</li>');
1.186     albertel 6149:     } elsif ($error =~ /CODE$/) {
                   6150: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6151: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6152: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6153: 	    $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 6154: 	}
1.224     albertel 6155: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6156: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6157: 	$r->print($message);
1.186     albertel 6158: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6159: 	$r->print("\n<br /> ");
1.194     albertel 6160: 	my $i=0;
1.273     albertel 6161: 	if ($error eq 'incorrectCODE' 
                   6162: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6163: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6164: 	    if ($closest > 0) {
                   6165: 		foreach my $testcode (@{$closest}) {
                   6166: 		    my $checked='';
1.401     albertel 6167: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6168: 		    $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' />");
                   6169: 		    $r->print("\n<br />");
                   6170: 		    $i++;
                   6171: 		}
1.194     albertel 6172: 	    }
                   6173: 	}
1.273     albertel 6174: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6175: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6176: 	    $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>");
                   6177: 	    $r->print("\n<br />");
                   6178: 	}
1.194     albertel 6179: 
1.188     albertel 6180: 	$r->print(<<ENDSCRIPT);
                   6181: <script type="text/javascript">
                   6182: function change_radio(field) {
1.190     albertel 6183:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6184:     var i;
                   6185:     for (i=0;i<slct.length;i++) {
                   6186:         if (slct[i].value==field) { slct[i].checked=true; }
                   6187:     }
                   6188: }
                   6189: </script>
                   6190: ENDSCRIPT
1.187     albertel 6191: 	my $href="/adm/pickcode?".
1.359     www      6192: 	   "form=".&escape("scantronupload").
                   6193: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6194: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6195: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6196: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6197: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6198: 	    $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')\" />");
                   6199: 	    $r->print("\n<br />");
                   6200: 	}
1.272     albertel 6201: 	$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 6202: 	$r->print("\n<br /><br />");
1.157     albertel 6203:     } elsif ($error eq 'doublebubble') {
                   6204: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6205: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6206: 		  join(',',@{$arg}).'" />');
1.242     albertel 6207: 	$r->print($message);
1.157     albertel 6208: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6209: 	foreach my $question (@{$arg}) {
                   6210: 	    my $selected=$$scan_record{"scantron.$question.answer"};
1.422     foxr     6211: 	    &scantron_bubble_selector($r,$scan_config,$question,
                   6212: 				      split('',$selected));
1.157     albertel 6213: 	}
                   6214:     } elsif ($error eq 'missingbubble') {
                   6215: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6216: 	$r->print($message);
1.157     albertel 6217: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6218: 	$r->print("Some questions have no scanned bubbles\n");
                   6219: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6220: 		  join(',',@{$arg}).'" />');
                   6221: 	foreach my $question (@{$arg}) {
                   6222: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   6223: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   6224: 	}
                   6225:     } else {
                   6226: 	$r->print("\n<ul>");
                   6227:     }
                   6228:     $r->print("\n</li></ul>");
                   6229: 
                   6230: }
1.423     albertel 6231: 
                   6232: =pod
                   6233: 
                   6234: =item scantron_bubble_selector
                   6235:   
                   6236:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6237:    possibly showing the existing the selected bubbles if known
1.423     albertel 6238: 
                   6239:  Arguments:
                   6240:     $r           - Apache request object
                   6241:     $scan_config - hash from &get_scantron_config()
                   6242:     $quest       - number of the bubble line to make a corrector for
                   6243:     $selected    - array of letters of previously selected bubbles
                   6244:     $lines       - if present, number of bubble lines to show
                   6245: 
                   6246: =cut
                   6247: 
1.157     albertel 6248: sub scantron_bubble_selector {
1.422     foxr     6249:     my ($r,$scan_config,$quest,@selected, $lines)=@_;
1.157     albertel 6250:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6251: 
                   6252:     my $scmode=$$scan_config{'Qon'};
                   6253:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6254: 
1.422     foxr     6255: 
                   6256:     if (!defined($lines)) {
                   6257: 	$lines = 1;
                   6258:     }
                   6259:     my $total_lines = $lines*2;
1.157     albertel 6260:     my @alphabet=('A'..'Z');
1.422     foxr     6261:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6262: 
                   6263:     for (my $l = 0; $l < $lines; $l++) {
                   6264: 	if ($l != 0) {
                   6265: 	    $r->print('<tr>');
                   6266: 	}
                   6267: 
                   6268: 	# FIXME:  This loop probably has to be considerably more clever for
                   6269: 	#  multiline bubbles: User can multibubble by having bubbles in
                   6270: 	#  several lines.  User can skip lines legitimately etc. etc.
                   6271: 
                   6272: 	for (my $i=0;$i<$max;$i++) {
                   6273: 	    $r->print("\n".'<td align="center">');
                   6274: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6275: 		$r->print('X'); 
                   6276: 		shift(@selected) ;
                   6277: 	    } else { 
                   6278: 		$r->print('&nbsp;'); 
                   6279: 	    }
                   6280: 	    $r->print('</td>');
                   6281: 	    
                   6282: 	}
                   6283: 
                   6284: 	if ($l == 0) {
                   6285: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6286: 
                   6287: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6288: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6289: 	
                   6290: 	}
                   6291: 
                   6292: 	$r->print('</tr><tr>');
                   6293: 
                   6294: 	# FIXME: This may have to be a bit more clever for
                   6295: 	#        multiline questions (different values e.g..).
                   6296: 
                   6297: 	for (my $i=0;$i<$max;$i++) {
                   6298: 	    $r->print("\n".
                   6299: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6300: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6301: 	}
                   6302: 	$r->print('</tr>');
                   6303: 
                   6304: 	    
1.157     albertel 6305:     }
1.422     foxr     6306:     $r->print('</table>');
1.157     albertel 6307: }
                   6308: 
1.423     albertel 6309: =pod
                   6310: 
                   6311: =item num_matches
                   6312: 
1.424     albertel 6313:    Counts the number of characters that are the same between the two arguments.
                   6314: 
                   6315:  Arguments:
                   6316:    $orig - CODE from the scanline
                   6317:    $code - CODE to match against
                   6318: 
                   6319:  Returns:
                   6320:    $count - integer count of the number of same characters between the
                   6321:             two arguments
                   6322: 
1.423     albertel 6323: =cut
                   6324: 
1.194     albertel 6325: sub num_matches {
                   6326:     my ($orig,$code) = @_;
                   6327:     my @code=split(//,$code);
                   6328:     my @orig=split(//,$orig);
                   6329:     my $same=0;
                   6330:     for (my $i=0;$i<scalar(@code);$i++) {
                   6331: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6332:     }
                   6333:     return $same;
                   6334: }
                   6335: 
1.423     albertel 6336: =pod
                   6337: 
                   6338: =item scantron_get_closely_matching_CODEs
                   6339: 
1.424     albertel 6340:    Cycles through all CODEs and finds the set that has the greatest
                   6341:    number of same characters as the provided CODE
                   6342: 
                   6343:  Arguments:
                   6344:    $allcodes - hash ref returned by &get_codes()
                   6345:    $CODE     - CODE from the current scanline
                   6346: 
                   6347:  Returns:
                   6348:    2 element list
                   6349:     - first elements is number of how closely matching the best fit is 
                   6350:       (5 means best set has 5 matching characters)
                   6351:     - second element is an arrary ref containing the set of valid CODEs
                   6352:       that best fit the passed in CODE
                   6353: 
1.423     albertel 6354: =cut
                   6355: 
1.194     albertel 6356: sub scantron_get_closely_matching_CODEs {
                   6357:     my ($allcodes,$CODE)=@_;
                   6358:     my @CODEs;
                   6359:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6360: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6361:     }
                   6362: 
                   6363:     return ($#CODEs,$CODEs[-1]);
                   6364: }
                   6365: 
1.423     albertel 6366: =pod
                   6367: 
                   6368: =item get_codes
                   6369: 
1.424     albertel 6370:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6371:    set of remembered CODEs.
                   6372: 
                   6373:  Arguments:
                   6374:   $old_name - name of the set of remembered CODEs
                   6375:   $cdom     - domain of the course
                   6376:   $cnum     - internal course name
                   6377: 
                   6378:  Returns:
                   6379:   %allcodes - keys are the valid CODEs, values are all 1
                   6380: 
1.423     albertel 6381: =cut
                   6382: 
1.194     albertel 6383: sub get_codes {
1.280     foxr     6384:     my ($old_name, $cdom, $cnum) = @_;
                   6385:     if (!$old_name) {
                   6386: 	$old_name=$env{'form.scantron_CODElist'};
                   6387:     }
                   6388:     if (!$cdom) {
                   6389: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6390:     }
                   6391:     if (!$cnum) {
                   6392: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6393:     }
1.278     albertel 6394:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6395: 				    $cdom,$cnum);
                   6396:     my %allcodes;
                   6397:     if ($result{"type\0$old_name"} eq 'number') {
                   6398: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6399:     } else {
                   6400: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6401:     }
1.194     albertel 6402:     return %allcodes;
                   6403: }
                   6404: 
1.423     albertel 6405: =pod
                   6406: 
                   6407: =item scantron_validate_CODE
                   6408: 
1.424     albertel 6409:    Validates all scanlines in the selected file to not have any
                   6410:    invalid or underspecified CODEs and that none of the codes are
                   6411:    duplicated if this was requested.
                   6412: 
1.423     albertel 6413: =cut
                   6414: 
1.157     albertel 6415: sub scantron_validate_CODE {
                   6416:     my ($r,$currentphase) = @_;
1.257     albertel 6417:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6418:     if ($scantron_config{'CODElocation'} &&
                   6419: 	$scantron_config{'CODEstart'} &&
                   6420: 	$scantron_config{'CODElength'}) {
1.257     albertel 6421: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6422: 	    &FIXME_blow_up()
                   6423: 	}
                   6424:     } else {
                   6425: 	return (0,$currentphase+1);
                   6426:     }
                   6427:     
                   6428:     my %usedCODEs;
                   6429: 
1.194     albertel 6430:     my %allcodes=&get_codes();
1.186     albertel 6431: 
                   6432:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6433:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6434: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6435: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6436: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6437: 						 $scan_data);
                   6438: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6439: 	my $error=0;
1.224     albertel 6440: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6441: 	    &scantron_get_correction($r,$i,$scan_record,
                   6442: 				     \%scantron_config,
                   6443: 				     $line,'incorrectCODE',\%allcodes);
                   6444: 	    return(1,$currentphase);
                   6445: 	}
1.221     albertel 6446: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6447: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6448: 	    &scantron_get_correction($r,$i,$scan_record,
                   6449: 				     \%scantron_config,
1.194     albertel 6450: 				     $line,'incorrectCODE',\%allcodes);
                   6451: 	    return(1,$currentphase);
1.186     albertel 6452: 	}
1.214     albertel 6453: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6454: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6455: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6456: 	    &scantron_get_correction($r,$i,$scan_record,
                   6457: 				     \%scantron_config,
1.194     albertel 6458: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6459: 	    return(1,$currentphase);
1.186     albertel 6460: 	}
1.194     albertel 6461: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6462:     }
1.157     albertel 6463:     return (0,$currentphase+1);
                   6464: }
                   6465: 
1.423     albertel 6466: =pod
                   6467: 
                   6468: =item scantron_validate_doublebubble
                   6469: 
1.424     albertel 6470:    Validates all scanlines in the selected file to not have any
                   6471:    bubble lines with multiple bubbles marked.
                   6472: 
1.423     albertel 6473: =cut
                   6474: 
1.157     albertel 6475: sub scantron_validate_doublebubble {
                   6476:     my ($r,$currentphase) = @_;
                   6477:     #get student info
                   6478:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6479:     my %idmap=&username_to_idmap($classlist);
                   6480: 
                   6481:     #get scantron line setup
1.257     albertel 6482:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6483:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6484:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6485: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6486: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6487: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6488: 						 $scan_data);
                   6489: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6490: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6491: 				 'doublebubble',
                   6492: 				 $$scan_record{'scantron.doubleerror'});
                   6493:     	return (1,$currentphase);
                   6494:     }
                   6495:     return (0,$currentphase+1);
                   6496: }
                   6497: 
1.423     albertel 6498: =pod
                   6499: 
                   6500: =item scantron_get_maxbubble
                   6501: 
1.424     albertel 6502:    Returns the maximum number of bubble lines that are expected to
                   6503:    occur. Does this by walking the selected sequence rendering the
                   6504:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6505:    for what the current value of the problem counter is.
                   6506: 
                   6507:    Caches the result to $env{'form.scantron_maxbubble'}
                   6508: 
1.423     albertel 6509: =cut
                   6510: 
1.330     albertel 6511: sub scantron_get_maxbubble {    
1.257     albertel 6512:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6513: 	$env{'form.scantron_maxbubble'}) {
                   6514: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6515:     }
1.330     albertel 6516: 
1.191     albertel 6517:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6518:     my (undef,undef,$sequence)=
1.257     albertel 6519: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6520: 
1.191     albertel 6521:     my $map=$navmap->getResourceByUrl($sequence);
                   6522:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6523: 
                   6524:     &Apache::lonxml::clear_problem_counter();
                   6525: 
1.191     albertel 6526:     foreach my $resource (@resources) {
1.330     albertel 6527: 	my $result=&Apache::lonnet::ssi($resource->src(),
                   6528: 					('symb' => $resource->symb()));
1.191     albertel 6529:     }
                   6530:     &Apache::lonnet::delenv('scantron\.');
1.330     albertel 6531:     $env{'form.scantron_maxbubble'} =
                   6532: 	&Apache::lonxml::get_problem_counter()-1;
                   6533: 
1.257     albertel 6534:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6535: }
                   6536: 
1.423     albertel 6537: =pod
                   6538: 
                   6539: =item scantron_validate_missingbubbles
                   6540: 
1.424     albertel 6541:    Validates all scanlines in the selected file to not have any
                   6542:    bubble lines with missing bubbles that haven't been verified as missing.
                   6543: 
1.423     albertel 6544: =cut
                   6545: 
1.157     albertel 6546: sub scantron_validate_missingbubbles {
                   6547:     my ($r,$currentphase) = @_;
                   6548:     #get student info
                   6549:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6550:     my %idmap=&username_to_idmap($classlist);
                   6551: 
                   6552:     #get scantron line setup
1.257     albertel 6553:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6554:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6555:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6556:     if (!$max_bubble) { $max_bubble=2**31; }
                   6557:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6558: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6559: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6560: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6561: 						 $scan_data);
                   6562: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6563: 	my @to_correct;
                   6564: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6565: 	    if ($missing > $max_bubble) { next; }
                   6566: 	    push(@to_correct,$missing);
                   6567: 	}
                   6568: 	if (@to_correct) {
                   6569: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6570: 				     $line,'missingbubble',\@to_correct);
                   6571: 	    return (1,$currentphase);
                   6572: 	}
                   6573: 
                   6574:     }
                   6575:     return (0,$currentphase+1);
                   6576: }
                   6577: 
1.423     albertel 6578: =pod
                   6579: 
                   6580: =item scantron_process_students
                   6581: 
                   6582:    Routine that does the actual grading of the bubble sheet information.
                   6583: 
                   6584:    The parsed scanline hash is added to %env 
                   6585: 
                   6586:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6587:    foreach resource , with the form data of
                   6588: 
                   6589: 	'submitted'     =>'scantron' 
                   6590: 	'grade_target'  =>'grade',
                   6591: 	'grade_username'=> username of student
                   6592: 	'grade_domain'  => domain of student
                   6593: 	'grade_courseid'=> of course
                   6594: 	'grade_symb'    => symb of resource to grade
                   6595: 
                   6596:     This triggers a grading pass. The problem grading code takes care
                   6597:     of converting the bubbled letter information (now in %env) into a
                   6598:     valid submission.
                   6599: 
                   6600: =cut
                   6601: 
1.82      albertel 6602: sub scantron_process_students {
1.75      albertel 6603:     my ($r) = @_;
1.257     albertel 6604:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6605:     my ($symb)=&get_symb($r);
1.81      albertel 6606:     if (!$symb) {return '';}
1.324     albertel 6607:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6608: 
1.257     albertel 6609:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6610:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6611:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6612:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6613:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6614:     my $map=$navmap->getResourceByUrl($sequence);
                   6615:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6616: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6617:     my $result= <<SCANTRONFORM;
1.81      albertel 6618: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6619:   <input type="hidden" name="command" value="scantron_configphase" />
                   6620:   $default_form_data
                   6621: SCANTRONFORM
1.82      albertel 6622:     $r->print($result);
                   6623: 
                   6624:     my @delayqueue;
1.140     albertel 6625:     my %completedstudents;
                   6626:     
1.200     albertel 6627:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6628:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6629:  				    'Scantron Progress',$count,
1.195     albertel 6630: 				    'inline',undef,'scantronupload');
1.140     albertel 6631:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6632: 					  'Processing first student');
                   6633:     my $start=&Time::HiRes::time();
1.158     albertel 6634:     my $i=-1;
1.200     albertel 6635:     my ($uname,$udom,$started);
1.157     albertel 6636:     while ($i<$scanlines->{'count'}) {
                   6637:  	($uname,$udom)=('','');
                   6638:  	$i++;
1.200     albertel 6639:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6640:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 6641: 	if ($started) {
                   6642: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   6643: 						     'last student');
                   6644: 	}
                   6645: 	$started=1;
1.157     albertel 6646:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6647:  						 $scan_data);
                   6648:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   6649:  					      \%idmap,$i)) {
                   6650:   	    &scantron_add_delay(\@delayqueue,$line,
                   6651:  				'Unable to find a student that matches',1);
                   6652:  	    next;
                   6653:   	}
                   6654:  	if (exists $completedstudents{$uname}) {
                   6655:  	    &scantron_add_delay(\@delayqueue,$line,
                   6656:  				'Student '.$uname.' has multiple sheets',2);
                   6657:  	    next;
                   6658:  	}
                   6659:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 6660: 
                   6661: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 6662:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 6663: 
                   6664: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   6665: 	    &scantron_putfile($scanlines,$scan_data);
                   6666: 	}
1.161     albertel 6667: 	
                   6668: 	my $i=0;
1.83      albertel 6669: 	foreach my $resource (@resources) {
1.85      albertel 6670: 	    $i++;
1.193     albertel 6671: 	    my %form=('submitted'     =>'scantron',
                   6672: 		      'grade_target'  =>'grade',
                   6673: 		      'grade_username'=>$uname,
                   6674: 		      'grade_domain'  =>$udom,
1.257     albertel 6675: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 6676: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 6677: 	    if (exists($scan_record->{'scantron.CODE'})
                   6678: 		&& 
                   6679: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 6680: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 6681: 	    } else {
                   6682: 		$form{'CODE'}='';
1.193     albertel 6683: 	    }
                   6684: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 6685: 	    if ($result ne '') {
                   6686: 		&Apache::lonnet::logthis("scantron grading error -> $result");
1.257     albertel 6687: 		&Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
1.227     albertel 6688: 	    }
1.213     albertel 6689: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 6690: 	}
1.140     albertel 6691: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 6692: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 6693:     } continue {
1.330     albertel 6694: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 6695: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 6696:     }
1.140     albertel 6697:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 6698: #    my $lasttime = &Time::HiRes::time()-$start;
                   6699: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 6700: 
1.200     albertel 6701:     $r->print("</form>");
1.324     albertel 6702:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 6703:     return '';
1.75      albertel 6704: }
1.157     albertel 6705: 
1.423     albertel 6706: =pod
                   6707: 
                   6708: =item scantron_upload_scantron_data
                   6709: 
                   6710:     Creates the screen for adding a new bubble sheet data file to a course.
                   6711: 
                   6712: =cut
                   6713: 
1.157     albertel 6714: sub scantron_upload_scantron_data {
                   6715:     my ($r)=@_;
1.257     albertel 6716:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 6717:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 6718: 							  'domainid',
                   6719: 							  'coursename');
1.257     albertel 6720:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 6721: 						   'domainid');
1.324     albertel 6722:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 6723:     $r->print(<<UPLOAD);
                   6724: <script type="text/javascript" language="javascript">
                   6725:     function checkUpload(formname) {
                   6726: 	if (formname.upfile.value == "") {
                   6727: 	    alert("Please use the browse button to select a file from your local directory.");
                   6728: 	    return false;
                   6729: 	}
                   6730: 	formname.submit();
                   6731:     }
                   6732: </script>
                   6733: 
                   6734: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 6735: $default_form_data
1.181     albertel 6736: <table>
                   6737: <tr><td>$select_link </td></tr>
                   6738: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   6739: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   6740: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   6741: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   6742: </table>
1.157     albertel 6743: <input name='command' value='scantronupload_save' type='hidden' />
                   6744: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   6745: </form>
                   6746: UPLOAD
                   6747:     return '';
                   6748: }
                   6749: 
1.423     albertel 6750: =pod
                   6751: 
                   6752: =item scantron_upload_scantron_data_save
                   6753: 
                   6754:    Adds a provided bubble information data file to the course if user
                   6755:    has the correct privileges to do so.  
                   6756: 
                   6757: =cut
                   6758: 
1.157     albertel 6759: sub scantron_upload_scantron_data_save {
                   6760:     my($r)=@_;
1.324     albertel 6761:     my ($symb)=&get_symb($r,1);
1.182     albertel 6762:     my $doanotherupload=
                   6763: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   6764: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   6765: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   6766: 	'</form>'."\n";
1.257     albertel 6767:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 6768: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 6769: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 6770: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 6771: 	if ($symb) {
1.324     albertel 6772: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 6773: 	} else {
                   6774: 	    $r->print($doanotherupload);
                   6775: 	}
1.162     albertel 6776: 	return '';
                   6777:     }
1.257     albertel 6778:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       6779:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 6780:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 6781:     #FIXME
                   6782:     #copied from lonnet::userfileupload()
                   6783:     #make that function able to target a specified course
                   6784:     # Replace Windows backslashes by forward slashes
                   6785:     $fname=~s/\\/\//g;
                   6786:     # Get rid of everything but the actual filename
                   6787:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   6788:     # Replace spaces by underscores
                   6789:     $fname=~s/\s+/\_/g;
                   6790:     # Replace all other weird characters by nothing
                   6791:     $fname=~s/[^\w\.\-]//g;
                   6792:     # See if there is anything left
                   6793:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       6794:     my $uploadedfile=$fname;
1.157     albertel 6795:     $fname='scantron_orig_'.$fname;
1.257     albertel 6796:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 6797: 	$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 6798:     } else {
1.275     albertel 6799: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 6800: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 6801: 	    $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 6802: 	} else {
1.398     albertel 6803: 	    $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 6804: 	}
                   6805:     }
1.174     albertel 6806:     if ($symb) {
1.209     ng       6807: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 6808:     } else {
1.182     albertel 6809: 	$r->print($doanotherupload);
1.174     albertel 6810:     }
1.157     albertel 6811:     return '';
                   6812: }
                   6813: 
1.423     albertel 6814: =pod
                   6815: 
                   6816: =item valid_file
                   6817: 
1.424     albertel 6818:    Validates that the requested bubble data file exists in the course.
1.423     albertel 6819: 
                   6820: =cut
                   6821: 
1.202     albertel 6822: sub valid_file {
                   6823:     my ($requested_file)=@_;
                   6824:     foreach my $filename (sort(&scantron_filenames())) {
                   6825: 	if ($requested_file eq $filename) { return 1; }
                   6826:     }
                   6827:     return 0;
                   6828: }
                   6829: 
1.423     albertel 6830: =pod
                   6831: 
                   6832: =item scantron_download_scantron_data
                   6833: 
                   6834:    Shows a list of the three internal files (original, corrected,
                   6835:    skipped) for a specific bubble sheet data file that exists in the
                   6836:    course.
                   6837: 
                   6838: =cut
                   6839: 
1.202     albertel 6840: sub scantron_download_scantron_data {
                   6841:     my ($r)=@_;
1.324     albertel 6842:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 6843:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6844:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6845:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 6846:     if (! &valid_file($file)) {
                   6847: 	$r->print(<<ERROR);
                   6848: 	<p>
                   6849: 	    The requested file name was invalid.
                   6850:         </p>
                   6851: ERROR
1.324     albertel 6852: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 6853: 	return;
                   6854:     }
                   6855:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   6856:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   6857:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   6858:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   6859:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   6860:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   6861:     $r->print(<<DOWNLOAD);
                   6862:     <p>
                   6863: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   6864:     </p>
                   6865:     <p>
                   6866: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   6867:     </p>
                   6868:     <p>
                   6869: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   6870:     </p>
                   6871: DOWNLOAD
1.324     albertel 6872:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 6873:     return '';
                   6874: }
1.157     albertel 6875: 
1.423     albertel 6876: =pod
                   6877: 
                   6878: =back
                   6879: 
                   6880: =cut
                   6881: 
1.75      albertel 6882: #-------- end of section for handling grading scantron forms -------
                   6883: #
                   6884: #-------------------------------------------------------------------
                   6885: 
1.72      ng       6886: #-------------------------- Menu interface -------------------------
                   6887: #
                   6888: #--- Show a Grading Menu button - Calls the next routine ---
                   6889: sub show_grading_menu_form {
1.324     albertel 6890:     my ($symb)=@_;
1.125     ng       6891:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 6892: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 6893: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       6894: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   6895: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   6896: 	'</form>'."\n";
                   6897:     return $result;
                   6898: }
                   6899: 
1.77      ng       6900: # -- Retrieve choices for grading form
                   6901: sub savedState {
                   6902:     my %savedState = ();
1.257     albertel 6903:     if ($env{'form.saveState'}) {
                   6904: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       6905: 	    my ($key,$value) = split(/=/,$_,2);
                   6906: 	    $savedState{$key} = $value;
                   6907: 	}
                   6908:     }
                   6909:     return \%savedState;
                   6910: }
1.76      ng       6911: 
1.72      ng       6912: #--- Displays the main menu page -------
                   6913: sub gradingmenu {
                   6914:     my ($request) = @_;
1.324     albertel 6915:     my ($symb)=&get_symb($request);
1.72      ng       6916:     if (!$symb) {return '';}
1.76      ng       6917:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       6918: 
                   6919:     $request->print(<<GRADINGMENUJS);
                   6920: <script type="text/javascript" language="javascript">
1.116     ng       6921:     function checkChoice(formname,val,cmdx) {
                   6922: 	if (val <= 2) {
                   6923: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       6924: 	    var cmdsave = cmd;
1.116     ng       6925: 	} else {
                   6926: 	    cmd = cmdx;
1.118     ng       6927: 	    cmdsave = 'submission';
1.116     ng       6928: 	}
                   6929: 	formname.command.value = cmd;
1.118     ng       6930: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 6931: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       6932: 	if (val < 5) formname.submit();
                   6933: 	if (val == 5) {
1.72      ng       6934: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   6935: 	    formname.submit();
                   6936: 	}
1.238     albertel 6937: 	if (val < 7) formname.submit();
1.72      ng       6938:     }
                   6939: 
                   6940:     function checkReceiptNo(formname,nospace) {
                   6941: 	var receiptNo = formname.receipt.value;
                   6942: 	var checkOpt = false;
                   6943: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   6944: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   6945: 	if (checkOpt) {
                   6946: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   6947: 	    formname.receipt.value = "";
                   6948: 	    formname.receipt.focus();
                   6949: 	    return false;
                   6950: 	}
                   6951: 	return true;
                   6952:     }
                   6953: </script>
                   6954: GRADINGMENUJS
1.118     ng       6955:     &commonJSfunctions($request);
1.398     albertel 6956:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
1.324     albertel 6957:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       6958:     $result.=$table;
1.76      ng       6959:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       6960:     my $savedState = &savedState();
1.118     ng       6961:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       6962:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       6963:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       6964:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       6965: 
                   6966:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 6967: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       6968: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   6969: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       6970: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       6971: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       6972: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       6973: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   6974: 
1.326     albertel 6975:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   6976: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
1.72      ng       6977: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       6978: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   6979: 
1.326     albertel 6980:     $result.='<table width="100%" border="0">';
1.116     ng       6981:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.429     banghart 6982: 	'&nbsp;'.&mt('Select Section').': <select name="section" multiple="multiple" size="3">'."\n";
1.116     ng       6983:     if (ref($sections)) {
1.155     albertel 6984: 	foreach (sort (@$sections)) {
                   6985: 	    $result.='<option value="'.$_.'" '.
1.401     albertel 6986: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
1.155     albertel 6987: 	}
1.116     ng       6988:     }
1.401     albertel 6989:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.116     ng       6990: 
1.401     albertel 6991:     $result.=&mt('Student Status').':'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
1.72      ng       6992: 
1.116     ng       6993:     $result.='</td></tr>';
                   6994: 
1.288     albertel 6995:     $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
1.118     ng       6996: 	'<input type="radio" name="radioChoice" value="submission" '.
1.401     albertel 6997: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 6998: 	'</label> <select name="submitonly">'.
1.145     albertel 6999: 	'<option value="yes" '.
1.401     albertel 7000: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
1.301     albertel 7001: 	'<option value="queued" '.
1.401     albertel 7002: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
1.145     albertel 7003: 	'<option value="graded" '.
1.401     albertel 7004: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 7005: 	'<option value="incorrect" '.
1.401     albertel 7006: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 7007: 	'<option value="all" '.
1.401     albertel 7008: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       7009: 
1.116     ng       7010:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.288     albertel 7011: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.401     albertel 7012: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7013: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       7014: 
1.118     ng       7015:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
1.288     albertel 7016: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.401     albertel 7017: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7018: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       7019: 
1.116     ng       7020:     $result.='<tr bgcolor="#ffffe6"><td><br />'.
1.126     ng       7021: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       7022: 	'</td></tr></table>'."\n";
                   7023: 
                   7024:     $result.='</td><td valign="top">';
                   7025: 
1.326     albertel 7026:     $result.='<table width="100%" border="0">';
1.116     ng       7027:     $result.='<tr bgcolor="#ffffe6"><td>'.
1.184     www      7028: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   7029: 	' '.&mt('scores from file').' </td></tr>'."\n";
1.72      ng       7030: 
1.404     www      7031:     $result.='<tr bgcolor="#ffffe6"><td>'.
                   7032:         '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
                   7033:         ' '.&mt('clicker file').' </td></tr>'."\n";
1.400     www      7034: 
1.75      albertel 7035:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.116     ng       7036: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
1.184     www      7037: 	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
1.75      albertel 7038: 
1.257     albertel 7039:     if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
1.72      ng       7040: 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.184     www      7041: 	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   7042: 	    ' '.&mt('receipt').': '.
1.257     albertel 7043: 	    &Apache::lonnet::recprefix($env{'request.course.id'}).
1.326     albertel 7044: 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
1.72      ng       7045: 	    '</td></tr>'."\n";
                   7046:     } 
1.238     albertel 7047:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7048: 	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   7049: 	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
1.279     albertel 7050:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7051: 	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   7052: 	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
1.44      ng       7053: 
1.401     albertel 7054:     $result.='</table>'."\n".
1.72      ng       7055: 	'</td></tr></table>'."\n".
1.401     albertel 7056: 	'</td></tr></table></form>'."\n";
1.44      ng       7057:     return $result;
1.2       albertel 7058: }
                   7059: 
1.285     albertel 7060: sub reset_perm {
                   7061:     undef(%perm);
                   7062: }
                   7063: 
                   7064: sub init_perm {
                   7065:     &reset_perm();
1.300     albertel 7066:     foreach my $test_perm ('vgr','mgr','opa') {
                   7067: 
                   7068: 	my $scope = $env{'request.course.id'};
                   7069: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7070: 
                   7071: 	    $scope .= '/'.$env{'request.course.sec'};
                   7072: 	    if ( $perm{$test_perm}=
                   7073: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7074: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7075: 	    } else {
                   7076: 		delete($perm{$test_perm});
                   7077: 	    }
1.285     albertel 7078: 	}
                   7079:     }
                   7080: }
                   7081: 
1.400     www      7082: sub gather_clicker_ids {
1.408     albertel 7083:     my %clicker_ids;
1.400     www      7084: 
                   7085:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7086: 
                   7087:     # Set up a couple variables.
1.407     albertel 7088:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7089:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.400     www      7090: 
1.407     albertel 7091:     foreach my $student (keys(%$classlist)) {
1.400     www      7092: 
1.407     albertel 7093:         my $username = $classlist->{$student}->[$username_idx];
                   7094:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7095:         my $clickers =
1.408     albertel 7096: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7097:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7098:             $id=~s/^[\#0]+//;
1.421     www      7099:             $id=~s/[\-\:]//g;
1.407     albertel 7100:             if (exists($clicker_ids{$id})) {
1.408     albertel 7101: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7102:             } else {
1.408     albertel 7103: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7104:             }
                   7105:         }
                   7106:     }
1.407     albertel 7107:     return %clicker_ids;
1.400     www      7108: }
                   7109: 
1.402     www      7110: sub gather_adv_clicker_ids {
1.408     albertel 7111:     my %clicker_ids;
1.402     www      7112:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7113:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7114:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7115:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7116:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7117:             my ($puname,$pudom)=split(/\:/,$person);
                   7118:             my $clickers =
1.408     albertel 7119: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7120:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7121: 		$id=~s/^[\#0]+//;
1.421     www      7122:                 $id=~s/[\-\:]//g;
1.408     albertel 7123: 		if (exists($clicker_ids{$id})) {
                   7124: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7125: 		} else {
                   7126: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7127: 		}
1.405     www      7128:             }
1.402     www      7129:         }
                   7130:     }
1.407     albertel 7131:     return %clicker_ids;
1.402     www      7132: }
                   7133: 
1.413     www      7134: sub clicker_grading_parameters {
                   7135:     return ('gradingmechanism' => 'scalar',
                   7136:             'upfiletype' => 'scalar',
                   7137:             'specificid' => 'scalar',
                   7138:             'pcorrect' => 'scalar',
                   7139:             'pincorrect' => 'scalar');
                   7140: }
                   7141: 
1.400     www      7142: sub process_clicker {
                   7143:     my ($r)=@_;
                   7144:     my ($symb)=&get_symb($r);
                   7145:     if (!$symb) {return '';}
                   7146:     my $result=&checkforfile_js();
                   7147:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7148:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7149:     $result.=$table;
                   7150:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7151:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7152:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7153:         '.</b></td></tr>'."\n";
                   7154:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7155: # Attempt to restore parameters from last session, set defaults if not present
                   7156:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7157:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7158:                                                  \%Saveable_Parameters);
                   7159:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7160:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7161:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7162:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7163: 
                   7164:     my %checked;
                   7165:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7166:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7167:           $checked{$gradingmechanism}="checked='checked'";
                   7168:        }
                   7169:     }
                   7170: 
1.400     www      7171:     my $upload=&mt("Upload File");
                   7172:     my $type=&mt("Type");
1.402     www      7173:     my $attendance=&mt("Award points just for participation");
                   7174:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7175:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7176:     my $pcorrect=&mt("Percentage points for correct solution");
                   7177:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7178:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7179: 						   ('iclicker' => 'i>clicker',
                   7180:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7181:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7182:     $result.=<<ENDUPFORM;
1.402     www      7183: <script type="text/javascript">
                   7184: function sanitycheck() {
                   7185: // Accept only integer percentages
                   7186:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7187:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7188: // Find out grading choice
                   7189:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7190:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7191:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7192:       }
                   7193:    }
                   7194: // By default, new choice equals user selection
                   7195:    newgradingchoice=gradingchoice;
                   7196: // Not good to give more points for false answers than correct ones
                   7197:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7198:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7199:    }
                   7200: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7201:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7202:       document.forms.gradesupload.pcorrect.value=100;
                   7203:       document.forms.gradesupload.pincorrect.value=100;
                   7204:    }
                   7205: // If the values are different, cannot be attendance only
                   7206:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7207:        (gradingchoice=='attendance')) {
                   7208:        newgradingchoice='personnel';
                   7209:    }
                   7210: // Change grading choice to new one
                   7211:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7212:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7213:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7214:       } else {
                   7215:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7216:       }
                   7217:    }
                   7218: // Remember the old state
                   7219:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7220: }
                   7221: </script>
1.400     www      7222: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7223: <input type="hidden" name="symb" value="$symb" />
                   7224: <input type="hidden" name="command" value="processclickerfile" />
                   7225: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7226: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7227: <input type="file" name="upfile" size="50" />
                   7228: <br /><label>$type: $selectform</label>
1.413     www      7229: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
                   7230: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
                   7231: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
1.414     www      7232: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7233: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7234: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7235: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7236: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7237: </form>
                   7238: ENDUPFORM
                   7239:     $result.='</td></tr></table>'."\n".
                   7240:              '</td></tr></table><br /><br />'."\n";
                   7241:     $result.=&show_grading_menu_form($symb);
                   7242:     return $result;
                   7243: }
                   7244: 
                   7245: sub process_clicker_file {
                   7246:     my ($r)=@_;
                   7247:     my ($symb)=&get_symb($r);
                   7248:     if (!$symb) {return '';}
1.413     www      7249: 
                   7250:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7251:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7252:                                               \%Saveable_Parameters);
                   7253: 
1.400     www      7254:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7255:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7256: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7257: 	return $result.&show_grading_menu_form($symb);
1.404     www      7258:     }
1.407     albertel 7259:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7260:     my %correct_ids;
1.404     www      7261:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7262: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7263:     }
                   7264:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7265: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7266: 	   $correct_id=~tr/a-z/A-Z/;
                   7267: 	   $correct_id=~s/\s//gs;
                   7268: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7269:            $correct_id=~s/[\-\:]//g;
1.414     www      7270:            if ($correct_id) {
                   7271: 	      $correct_ids{$correct_id}='specified';
                   7272:            }
                   7273:         }
1.400     www      7274:     }
1.404     www      7275:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7276: 	$result.=&mt('Score based on attendance only');
1.404     www      7277:     } else {
1.408     albertel 7278: 	my $number=0;
1.411     www      7279: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7280: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7281: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7282: 	    if ($correct_ids{$id} eq 'specified') {
                   7283: 		$result.=&mt('specified');
                   7284: 	    } else {
                   7285: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7286: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7287: 	    }
                   7288: 	    $number++;
                   7289: 	}
1.411     www      7290:         $result.="</p>\n";
1.408     albertel 7291: 	if ($number==0) {
                   7292: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7293: 	    return $result.&show_grading_menu_form($symb);
                   7294: 	}
1.404     www      7295:     }
1.405     www      7296:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7297:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7298: 		     '<span class="LC_error">',
                   7299: 		     '</span>',
                   7300: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7301:         return $result.&show_grading_menu_form($symb);
                   7302:     }
1.410     www      7303: 
                   7304: # Were able to get all the info needed, now analyze the file
                   7305: 
1.411     www      7306:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7307:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7308:     my $heading=&mt('Scanning clicker file');
                   7309:     $result.=(<<ENDHEADER);
                   7310: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7311: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7312: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7313: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7314: <input type="hidden" name="symb" value="$symb" />
                   7315: <input type="hidden" name="command" value="assignclickergrades" />
                   7316: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7317: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7318: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7319: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7320: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7321: ENDHEADER
1.408     albertel 7322:     my %responses;
                   7323:     my @questiontitles;
1.405     www      7324:     my $errormsg='';
                   7325:     my $number=0;
                   7326:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7327: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7328:     }
1.419     www      7329:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7330:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7331:     }
1.411     www      7332:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7333:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   7334:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7335:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7336:              '<br />';
1.414     www      7337: # Remember Question Titles
                   7338: # FIXME: Possibly need delimiter other than ":"
                   7339:     for (my $i=0;$i<$number;$i++) {
                   7340:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7341:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7342:     }
1.411     www      7343:     my $correct_count=0;
                   7344:     my $student_count=0;
                   7345:     my $unknown_count=0;
1.414     www      7346: # Match answers with usernames
                   7347: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7348:     foreach my $id (keys(%responses)) {
1.410     www      7349:        if ($correct_ids{$id}) {
1.414     www      7350:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7351:           $correct_count++;
1.410     www      7352:        } elsif ($clicker_ids{$id}) {
                   7353:           $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7354:           $student_count++;
1.410     www      7355:        } else {
1.411     www      7356:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7357:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7358:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7359:                    "\n".&mt("Domain").": ".
                   7360:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7361:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7362:           $unknown_count++;
1.410     www      7363:        }
1.405     www      7364:     }
1.412     www      7365:     $result.='<hr />'.
                   7366:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7367:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7368:        if ($correct_count==0) {
                   7369:           $errormsg.="Found no correct answers answers for grading!";
                   7370:        } elsif ($correct_count>1) {
1.414     www      7371:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7372:        }
                   7373:     }
1.428     www      7374:     if ($number<1) {
                   7375:        $errormsg.="Found no questions.";
                   7376:     }
1.412     www      7377:     if ($errormsg) {
                   7378:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7379:     } else {
                   7380:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7381:     }
                   7382:     $result.='</form></td></tr></table>'."\n".
1.410     www      7383:              '</td></tr></table><br /><br />'."\n";
1.404     www      7384:     return $result.&show_grading_menu_form($symb);
1.400     www      7385: }
                   7386: 
1.405     www      7387: sub iclicker_eval {
1.406     www      7388:     my ($questiontitles,$responses)=@_;
1.405     www      7389:     my $number=0;
                   7390:     my $errormsg='';
                   7391:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7392:         my %components=&Apache::loncommon::record_sep($line);
                   7393:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7394: 	if ($entries[0] eq 'Question') {
                   7395: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7396: 		$$questiontitles[$number]=$entries[$i];
                   7397: 		$number++;
                   7398: 	    }
                   7399: 	}
                   7400: 	if ($entries[0]=~/^\#/) {
                   7401: 	    my $id=$entries[0];
                   7402: 	    my @idresponses;
                   7403: 	    $id=~s/^[\#0]+//;
                   7404: 	    for (my $i=0;$i<$number;$i++) {
                   7405: 		my $idx=3+$i*6;
                   7406: 		push(@idresponses,$entries[$idx]);
                   7407: 	    }
                   7408: 	    $$responses{$id}=join(',',@idresponses);
                   7409: 	}
1.405     www      7410:     }
                   7411:     return ($errormsg,$number);
                   7412: }
                   7413: 
1.419     www      7414: sub interwrite_eval {
                   7415:     my ($questiontitles,$responses)=@_;
                   7416:     my $number=0;
                   7417:     my $errormsg='';
1.420     www      7418:     my $skipline=1;
                   7419:     my $questionnumber=0;
                   7420:     my %idresponses=();
1.419     www      7421:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   7422:         my %components=&Apache::loncommon::record_sep($line);
                   7423:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      7424:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   7425:         if ($entries[1] eq 'Response') { $skipline=1; }
                   7426:         next if $skipline;
                   7427:         if ($entries[0]!=$questionnumber) {
                   7428:            $questionnumber=$entries[0];
                   7429:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   7430:            $number++;
1.419     www      7431:         }
1.420     www      7432:         my $id=$entries[4];
                   7433:         $id=~s/^[\#0]+//;
1.421     www      7434:         $id=~s/^v\d*\://i;
                   7435:         $id=~s/[\-\:]//g;
1.420     www      7436:         $idresponses{$id}[$number]=$entries[6];
                   7437:     }
                   7438:     foreach my $id (keys %idresponses) {
                   7439:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   7440:        $$responses{$id}=~s/^\s*\,//;
1.419     www      7441:     }
                   7442:     return ($errormsg,$number);
                   7443: }
                   7444: 
1.414     www      7445: sub assign_clicker_grades {
                   7446:     my ($r)=@_;
                   7447:     my ($symb)=&get_symb($r);
                   7448:     if (!$symb) {return '';}
1.416     www      7449: # See which part we are saving to
                   7450:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   7451: # FIXME: This should probably look for the first handgradeable part
                   7452:     my $part=$$partlist[0];
                   7453: # Start screen output
1.414     www      7454:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      7455: 
1.414     www      7456:     my $heading=&mt('Assigning grades based on clicker file');
                   7457:     $result.=(<<ENDHEADER);
                   7458: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7459: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7460: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7461: ENDHEADER
                   7462: # Get correct result
                   7463: # FIXME: Possibly need delimiter other than ":"
                   7464:     my @correct=();
1.415     www      7465:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   7466:     my $number=$env{'form.number'};
                   7467:     if ($gradingmechanism ne 'attendance') {
1.414     www      7468:        foreach my $key (keys(%env)) {
                   7469:           if ($key=~/^form\.correct\:/) {
                   7470:              my @input=split(/\,/,$env{$key});
                   7471:              for (my $i=0;$i<=$#input;$i++) {
                   7472:                  if (($correct[$i]) && ($input[$i]) &&
                   7473:                      ($correct[$i] ne $input[$i])) {
                   7474:                     $result.='<br /><span class="LC_warning">'.
                   7475:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   7476:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   7477:                  } elsif ($input[$i]) {
                   7478:                     $correct[$i]=$input[$i];
                   7479:                  }
                   7480:              }
                   7481:           }
                   7482:        }
1.415     www      7483:        for (my $i=0;$i<$number;$i++) {
1.414     www      7484:           if (!$correct[$i]) {
                   7485:              $result.='<br /><span class="LC_error">'.
                   7486:                       &mt('No correct result given for question "[_1]"!',
                   7487:                           $env{'form.question:'.$i}).'</span>';
                   7488:           }
                   7489:        }
                   7490:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   7491:     }
                   7492: # Start grading
1.415     www      7493:     my $pcorrect=$env{'form.pcorrect'};
                   7494:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      7495:     my $storecount=0;
1.415     www      7496:     foreach my $key (keys(%env)) {
1.420     www      7497:        my $user='';
1.415     www      7498:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      7499:           $user=$1;
                   7500:        }
                   7501:        if ($key=~/^form\.unknown\:(.*)$/) {
                   7502:           my $id=$1;
                   7503:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   7504:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
                   7505:           }
                   7506:        }
                   7507:        if ($user) { 
1.415     www      7508:           my @answer=split(/\,/,$env{$key});
                   7509:           my $sum=0;
                   7510:           for (my $i=0;$i<$number;$i++) {
                   7511:              if ($answer[$i]) {
                   7512:                 if ($gradingmechanism eq 'attendance') {
                   7513:                    $sum+=$pcorrect;
                   7514:                 } else {
                   7515:                    if ($answer[$i] eq $correct[$i]) {
                   7516:                       $sum+=$pcorrect;
                   7517:                    } else {
                   7518:                       $sum+=$pincorrect;
                   7519:                    }
                   7520:                 }
                   7521:              }
                   7522:           }
1.416     www      7523:           my $ave=$sum/(100*$number);
                   7524: # Store
                   7525:           my ($username,$domain)=split(/\:/,$user);
                   7526:           my %grades=();
                   7527:           $grades{"resource.$part.solved"}='correct_by_override';
                   7528:           $grades{"resource.$part.awarded"}=$ave;
                   7529:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   7530:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   7531:                                                  $env{'request.course.id'},
                   7532:                                                  $domain,$username);
                   7533:           if ($returncode ne 'ok') {
                   7534:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   7535:           } else {
                   7536:              $storecount++;
                   7537:           }
1.415     www      7538:        }
                   7539:     }
                   7540: # We are done
1.416     www      7541:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   7542:              '</td></tr></table>'."\n".
1.414     www      7543:              '</td></tr></table><br /><br />'."\n";
                   7544:     return $result.&show_grading_menu_form($symb);
                   7545: }
                   7546: 
1.1       albertel 7547: sub handler {
1.41      ng       7548:     my $request=$_[0];
1.102     albertel 7549: 
1.434   ! albertel 7550:     &reset_caches();
1.257     albertel 7551:     if ($env{'browser.mathml'}) {
1.141     www      7552: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       7553:     } else {
1.141     www      7554: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       7555:     }
                   7556:     $request->send_http_header;
1.44      ng       7557:     return '' if $request->header_only;
1.41      ng       7558:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 7559:     my $symb=&get_symb($request,1);
1.160     albertel 7560:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   7561:     my $command=$commands[0];
                   7562:     if ($#commands > 0) {
                   7563: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   7564:     }
1.353     albertel 7565:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 7566:     if ($symb eq '' && $command eq '') {
1.257     albertel 7567: 	if ($env{'user.adv'}) {
                   7568: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   7569: 		($env{'form.codethree'})) {
                   7570: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   7571: 		    $env{'form.codethree'};
1.41      ng       7572: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   7573: 		    &Apache::lonnet::checkin($token);
                   7574: 		if ($tsymb) {
1.137     albertel 7575: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       7576: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 7577: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   7578: 					  ('grade_username' => $tuname,
                   7579: 					   'grade_domain' => $tudom,
                   7580: 					   'grade_courseid' => $tcrsid,
                   7581: 					   'grade_symb' => $tsymb)));
1.41      ng       7582: 		    } else {
1.45      ng       7583: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 7584: 		    }
1.41      ng       7585: 		} else {
1.45      ng       7586: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       7587: 		}
1.14      www      7588: 	    } else {
1.41      ng       7589: 		$request->print(&Apache::lonxml::tokeninputfield());
                   7590: 	    }
                   7591: 	}
                   7592:     } else {
1.285     albertel 7593: 	&init_perm();
1.104     albertel 7594: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 7595: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 7596: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       7597: 	    &pickStudentPage($request);
1.103     albertel 7598: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       7599: 	    &displayPage($request);
1.104     albertel 7600: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       7601: 	    &updateGradeByPage($request);
1.104     albertel 7602: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       7603: 	    &processGroup($request);
1.104     albertel 7604: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.41      ng       7605: 	    $request->print(&gradingmenu($request));
1.104     albertel 7606: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       7607: 	    $request->print(&viewgrades($request));
1.104     albertel 7608: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       7609: 	    $request->print(&processHandGrade($request));
1.106     albertel 7610: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       7611: 	    $request->print(&editgrades($request));
1.106     albertel 7612: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       7613: 	    $request->print(&verifyreceipt($request));
1.400     www      7614:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   7615:             $request->print(&process_clicker($request));
                   7616:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   7617:             $request->print(&process_clicker_file($request));
1.414     www      7618:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   7619:             $request->print(&assign_clicker_grades($request));
1.106     albertel 7620: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       7621: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 7622: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       7623: 	    $request->print(&csvupload($request));
1.106     albertel 7624: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       7625: 	    $request->print(&csvuploadmap($request));
1.246     albertel 7626: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 7627: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 7628: 		$request->print(&csvuploadoptions($request));
1.41      ng       7629: 	    } else {
1.257     albertel 7630: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   7631: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       7632: 		} else {
1.257     albertel 7633: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       7634: 		}
                   7635: 		$request->print(&csvuploadmap($request));
                   7636: 	    }
1.246     albertel 7637: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   7638: 	    $request->print(&csvuploadassign($request));
1.106     albertel 7639: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 7640: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 7641:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   7642:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 7643: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   7644: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 7645: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 7646: 	    $request->print(&scantron_process_students($request));
1.157     albertel 7647:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 7648:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   7649: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 7650:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 7651:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 7652:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   7653: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 7654:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 7655:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 7656: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 7657:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 7658: 	} elsif ($command) {
1.157     albertel 7659: 	    $request->print("Access Denied ($command)");
1.26      albertel 7660: 	}
1.2       albertel 7661:     }
1.353     albertel 7662:     $request->print(&Apache::loncommon::end_page());
1.434   ! albertel 7663:     &reset_caches();
1.44      ng       7664:     return '';
                   7665: }
                   7666: 
1.1       albertel 7667: 1;
                   7668: 
1.13      albertel 7669: __END__;

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