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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.432   ! banghart    4: # $Id: grades.pm,v 1.431 2007/08/21 18:48:18 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.103     albertel   48: my %perm=();
1.1       albertel   49: 
1.68      ng         50: # ----- These first few routines are general use routines.----
1.44      ng         51: #
1.146     albertel   52: # --- Retrieve the parts from the metadata file.---
1.44      ng         53: sub getpartlist {
1.324     albertel   54:     my ($symb) = @_;
                     55:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.146     albertel   56:     my $partorder = &Apache::lonnet::metadata($url, 'partorder');
                     57:     my @parts;
                     58:     if ($partorder) {
                     59: 	for my $part (split (/,/,$partorder)) {
                     60: 	    if (!&Apache::loncommon::check_if_partid_hidden($part,$symb)) {
                     61: 		push(@parts, $part);
                     62: 	    }
                     63: 	}	    
                     64:     } else {
                     65: 	my $metadata = &Apache::lonnet::metadata($url, 'packages');
                     66: 	foreach (split(/\,/,$metadata)) {
                     67: 	    if ($_ =~ /^part_(.*)$/) {
                     68: 		if (!&Apache::loncommon::check_if_partid_hidden($1,$symb)) {
                     69: 		    push(@parts, $1);
                     70: 		}
                     71: 	    }
1.41      ng         72: 	}
1.16      albertel   73:     }
1.146     albertel   74:     my @stores;
                     75:     foreach my $part (@parts) {
                     76: 	my (@metakeys) = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                     77: 	foreach my $key (@metakeys) {
                     78: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                     79: 	}
                     80:     }
                     81:     return @stores;
1.2       albertel   82: }
                     83: 
1.44      ng         84: # --- Get the symbolic name of a problem and the url
1.324     albertel   85: sub get_symb {
1.173     albertel   86:     my ($request,$silent) = @_;
1.257     albertel   87:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                     88:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel   89:     if ($symb eq '') { 
                     90: 	if (!$silent) {
                     91: 	    $request->print("Unable to handle ambiguous references:$url:.");
                     92: 	    return ();
                     93: 	}
                     94:     }
1.418     albertel   95:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel   96:     return ($symb);
1.32      ng         97: }
                     98: 
1.129     ng         99: #--- Format fullname, username:domain if different for display
                    100: #--- Use anywhere where the student names are listed
                    101: sub nameUserString {
                    102:     my ($type,$fullname,$uname,$udom) = @_;
                    103:     if ($type eq 'header') {
1.398     albertel  104: 	return '<b>&nbsp;Fullname&nbsp;</b><span class="LC_internal_info">(Username)</span>';
1.129     ng        105:     } else {
1.398     albertel  106: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    107: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        108:     }
                    109: }
                    110: 
1.44      ng        111: #--- Get the partlist and the response type for a given problem. ---
                    112: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        113: sub response_type {
1.324     albertel  114:     my ($symb) = shift;
1.377     albertel  115: 
                    116:     my $navmap = Apache::lonnavmaps::navmap->new();
                    117:     my $res = $navmap->getBySymb($symb);
                    118:     my $partlist = $res->parts();
1.392     albertel  119:     my %vPart = 
                    120: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  121:     my (%response_types,%handgrade);
                    122:     foreach my $part (@{ $partlist }) {
1.392     albertel  123: 	next if (%vPart && !exists($vPart{$part}));
                    124: 
1.377     albertel  125: 	my @types = $res->responseType($part);
                    126: 	my @ids = $res->responseIds($part);
                    127: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    128: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    129: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    130: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    131: 				     '.handgrade',$symb);
1.41      ng        132: 	}
                    133:     }
1.377     albertel  134:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        135: }
                    136: 
1.375     albertel  137: sub flatten_responseType {
                    138:     my ($responseType) = @_;
                    139:     my @part_response_id =
                    140: 	map { 
                    141: 	    my $part = $_;
                    142: 	    map {
                    143: 		[$part,$_]
                    144: 		} sort(keys(%{ $responseType->{$part} }));
                    145: 	} sort(keys(%$responseType));
                    146:     return @part_response_id;
                    147: }
                    148: 
1.207     albertel  149: sub get_display_part {
1.324     albertel  150:     my ($partID,$symb)=@_;
1.207     albertel  151:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    152:     if (defined($display) and $display ne '') {
1.398     albertel  153: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  154:     } else {
                    155: 	$display=$partID;
                    156:     }
                    157:     return $display;
                    158: }
1.269     raeburn   159: 
1.118     ng        160: #--- Show resource title
                    161: #--- and parts and response type
                    162: sub showResourceInfo {
1.324     albertel  163:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  164:     my $col=3;
                    165:     if ($checkboxes) { $col=4; }
1.398     albertel  166:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    167:     $result .='<table border="0">';
1.324     albertel  168:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        169:     my %resptype = ();
1.122     ng        170:     my $hdgrade='no';
1.154     albertel  171:     my %partsseen;
1.375     albertel  172:     foreach my $partID (sort keys(%$responseType)) {
                    173: 	foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
                    174: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    175: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    176: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    177: 	    $result.='<tr>';
                    178: 	    if ($checkboxes) {
                    179: 		if (exists($partsseen{$partID})) {
                    180: 		    $result.="<td>&nbsp;</td>";
                    181: 		} else {
1.401     albertel  182: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  183: 		}
                    184: 		$partsseen{$partID}=1;
1.154     albertel  185: 	    }
1.375     albertel  186: 	    my $display_part=&get_display_part($partID,$symb);
1.398     albertel  187: 	    $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
                    188: 		$resID.'</span></td>'.
1.375     albertel  189: 		'<td><b>Type: </b>'.$responsetype.'</td></tr>';
                    190: #	    '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
1.154     albertel  191: 	}
1.118     ng        192:     }
                    193:     $result.='</table>'."\n";
1.147     albertel  194:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        195: }
                    196: 
1.148     albertel  197: 
                    198: sub get_order {
                    199:     my ($partid,$respid,$symb,$uname,$udom)=@_;
                    200:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    201:     $url=&Apache::lonnet::clutter($url);
                    202:     my $subresult=&Apache::lonnet::ssi($url,
                    203: 				       ('grade_target' => 'analyze'),
                    204: 				       ('grade_domain' => $udom),
                    205: 				       ('grade_symb' => $symb),
                    206: 				       ('grade_courseid' => 
1.257     albertel  207: 					        $env{'request.course.id'}),
1.148     albertel  208: 				       ('grade_username' => $uname));
1.149     albertel  209:     (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
1.148     albertel  210:     my %analyze=&Apache::lonnet::str2hash($subresult);
                    211:     return ($analyze{"$partid.$respid.shown"});
                    212: }
1.118     ng        213: #--- Clean response type for display
1.335     albertel  214: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    215: #        response types only.
1.118     ng        216: sub cleanRecord {
1.336     albertel  217:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    218: 	$uname,$udom) = @_;
1.398     albertel  219:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  220:     if ($response =~ /^(option|rank)$/) {
                    221: 	my %answer=&Apache::lonnet::str2hash($answer);
                    222: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    223: 	my ($toprow,$bottomrow);
                    224: 	foreach my $foil (@$order) {
                    225: 	    if ($grading{$foil} == 1) {
                    226: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    227: 	    } else {
                    228: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    229: 	    }
1.398     albertel  230: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  231: 	}
                    232: 	return '<blockquote><table border="1">'.
                    233: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  234: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  235: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    236:     } elsif ($response eq 'match') {
                    237: 	my %answer=&Apache::lonnet::str2hash($answer);
                    238: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    239: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    240: 	my ($toprow,$middlerow,$bottomrow);
                    241: 	foreach my $foil (@$order) {
                    242: 	    my $item=shift(@items);
                    243: 	    if ($grading{$foil} == 1) {
                    244: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  245: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  246: 	    } else {
                    247: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  248: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  249: 	    }
1.398     albertel  250: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        251: 	}
1.126     ng        252: 	return '<blockquote><table border="1">'.
1.148     albertel  253: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  254: 	    '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
1.148     albertel  255: 	    $middlerow.'</tr>'.
1.398     albertel  256: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  257: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    258:     } elsif ($response eq 'radiobutton') {
                    259: 	my %answer=&Apache::lonnet::str2hash($answer);
                    260: 	my ($toprow,$bottomrow);
                    261: 	my $correct=($order->[0])+1;
                    262: 	for (my $i=1;$i<=$#$order;$i++) {
                    263: 	    my $foil=$order->[$i];
                    264: 	    if (exists($answer{$foil})) {
                    265: 		if ($i == $correct) {
                    266: 		    $toprow.='<td><b>true</b></td>';
                    267: 		} else {
                    268: 		    $toprow.='<td><i>true</i></td>';
                    269: 		}
                    270: 	    } else {
                    271: 		$toprow.='<td>false</td>';
                    272: 	    }
1.398     albertel  273: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  274: 	}
                    275: 	return '<blockquote><table border="1">'.
                    276: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  277: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  278: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    279:     } elsif ($response eq 'essay') {
1.257     albertel  280: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        281: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  282: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    283: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        284: 
1.257     albertel  285: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    286: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    287: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    288: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    289: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    290: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
1.122     ng        291: 	}
1.166     albertel  292: 	$answer =~ s-\n-<br />-g;
                    293: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  294:     } elsif ( $response eq 'organic') {
                    295: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    296: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    297: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    298: 	return $result;
1.335     albertel  299:     } elsif ( $response eq 'Task') {
                    300: 	if ( $answer eq 'SUBMITTED') {
                    301: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  302: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  303: 	    return $result;
                    304: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    305: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    306: 			       keys(%{$record}));
                    307: 	    return join('<br />',($version,@matches));
                    308: 			       
                    309: 			       
                    310: 	} else {
                    311: 	    my $result =
                    312: 		'<p>'
                    313: 		.&mt('Overall result: [_1]',
                    314: 		     $record->{$version."resource.$respid.$partid.status"})
                    315: 		.'</p>';
                    316: 	    
                    317: 	    $result .= '<ul>';
                    318: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    319: 			     keys(%{$record}));
                    320: 	    foreach my $grade (sort(@grade)) {
                    321: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    322: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    323: 				     $dim, $record->{$grade}).
                    324: 			  '</li>';
                    325: 	    }
                    326: 	    $result.='</ul>';
                    327: 	    return $result;
                    328: 	}
                    329:        
1.122     ng        330:     }
1.118     ng        331:     return $answer;
                    332: }
                    333: 
                    334: #-- A couple of common js functions
                    335: sub commonJSfunctions {
                    336:     my $request = shift;
                    337:     $request->print(<<COMMONJSFUNCTIONS);
                    338: <script type="text/javascript" language="javascript">
                    339:     function radioSelection(radioButton) {
                    340: 	var selection=null;
                    341: 	if (radioButton.length > 1) {
                    342: 	    for (var i=0; i<radioButton.length; i++) {
                    343: 		if (radioButton[i].checked) {
                    344: 		    return radioButton[i].value;
                    345: 		}
                    346: 	    }
                    347: 	} else {
                    348: 	    if (radioButton.checked) return radioButton.value;
                    349: 	}
                    350: 	return selection;
                    351:     }
                    352: 
                    353:     function pullDownSelection(selectOne) {
                    354: 	var selection="";
                    355: 	if (selectOne.length > 1) {
                    356: 	    for (var i=0; i<selectOne.length; i++) {
                    357: 		if (selectOne[i].selected) {
                    358: 		    return selectOne[i].value;
                    359: 		}
                    360: 	    }
                    361: 	} else {
1.138     albertel  362:             // only one value it must be the selected one
                    363: 	    return selectOne.value;
1.118     ng        364: 	}
                    365:     }
                    366: </script>
                    367: COMMONJSFUNCTIONS
                    368: }
                    369: 
1.44      ng        370: #--- Dumps the class list with usernames,list of sections,
                    371: #--- section, ids and fullnames for each user.
                    372: sub getclasslist {
1.76      ng        373:     my ($getsec,$filterlist) = @_;
1.291     albertel  374:     my @getsec;
                    375:     if (!ref($getsec)) {
                    376: 	if ($getsec ne '' && $getsec ne 'all') {
                    377: 	    @getsec=($getsec);
                    378: 	}
                    379:     } else {
                    380: 	@getsec=@{$getsec};
                    381:     }
                    382:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
                    383: 
1.56      matthew   384:     my $classlist=&Apache::loncoursedata::get_classlist();
1.49      albertel  385:     # Bail out if we were unable to get the classlist
1.56      matthew   386:     return if (! defined($classlist));
                    387:     #
                    388:     my %sections;
                    389:     my %fullnames;
1.205     matthew   390:     foreach my $student (keys(%$classlist)) {
                    391:         my $end      = 
                    392:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    393:         my $start    = 
                    394:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    395:         my $id       = 
                    396:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    397:         my $section  = 
                    398:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    399:         my $fullname = 
                    400:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    401:         my $status   = 
                    402:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.76      ng        403: 	# filter students according to status selected
1.257     albertel  404: 	if ($filterlist && $env{'form.Status'} ne 'Any') {
                    405: 	    if ($env{'form.Status'} ne $status) {
1.205     matthew   406: 		delete ($classlist->{$student});
1.76      ng        407: 		next;
                    408: 	    }
                    409: 	}
1.205     matthew   410: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  411: 	if (&canview($section)) {
1.291     albertel  412: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  413: 		$sections{$section}++;
1.205     matthew   414: 		$fullnames{$student}=$fullname;
1.103     albertel  415: 	    } else {
1.205     matthew   416: 		delete($classlist->{$student});
1.103     albertel  417: 	    }
                    418: 	} else {
1.205     matthew   419: 	    delete($classlist->{$student});
1.103     albertel  420: 	}
1.44      ng        421:     }
                    422:     my %seen = ();
1.56      matthew   423:     my @sections = sort(keys(%sections));
                    424:     return ($classlist,\@sections,\%fullnames);
1.44      ng        425: }
                    426: 
1.103     albertel  427: sub canmodify {
                    428:     my ($sec)=@_;
                    429:     if ($perm{'mgr'}) {
                    430: 	if (!defined($perm{'mgr_section'})) {
                    431: 	    # can modify whole class
                    432: 	    return 1;
                    433: 	} else {
                    434: 	    if ($sec eq $perm{'mgr_section'}) {
                    435: 		#can modify the requested section
                    436: 		return 1;
                    437: 	    } else {
                    438: 		# can't modify the request section
                    439: 		return 0;
                    440: 	    }
                    441: 	}
                    442:     }
                    443:     #can't modify
                    444:     return 0;
                    445: }
                    446: 
                    447: sub canview {
                    448:     my ($sec)=@_;
                    449:     if ($perm{'vgr'}) {
                    450: 	if (!defined($perm{'vgr_section'})) {
                    451: 	    # can modify whole class
                    452: 	    return 1;
                    453: 	} else {
                    454: 	    if ($sec eq $perm{'vgr_section'}) {
                    455: 		#can modify the requested section
                    456: 		return 1;
                    457: 	    } else {
                    458: 		# can't modify the request section
                    459: 		return 0;
                    460: 	    }
                    461: 	}
                    462:     }
                    463:     #can't modify
                    464:     return 0;
                    465: }
                    466: 
1.44      ng        467: #--- Retrieve the grade status of a student for all the parts
                    468: sub student_gradeStatus {
1.324     albertel  469:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  470:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        471:     my %partstatus = ();
                    472:     foreach (@$partlist) {
1.128     ng        473: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        474: 	$status              = 'nothing' if ($status eq '');
                    475: 	$partstatus{$_}      = $status;
                    476: 	my $subkey           = "resource.$_.submitted_by";
                    477: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    478:     }
                    479:     return %partstatus;
                    480: }
                    481: 
1.45      ng        482: # hidden form and javascript that calls the form
                    483: # Use by verifyscript and viewgrades
                    484: # Shows a student's view of problem and submission
                    485: sub jscriptNform {
1.324     albertel  486:     my ($symb) = @_;
1.45      ng        487:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    488: 	'    function viewOneStudent(user,domain) {'."\n".
                    489: 	'	document.onestudent.student.value = user;'."\n".
                    490: 	'	document.onestudent.userdom.value = domain;'."\n".
                    491: 	'	document.onestudent.submit();'."\n".
                    492: 	'    }'."\n".
                    493: 	'</script>'."\n";
                    494:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  495: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  496: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    497: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
                    498: 	'<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.45      ng        499: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    500: 	'<input type="hidden" name="student" value="" />'."\n".
                    501: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    502: 	'</form>'."\n";
                    503:     return $jscript;
                    504: }
1.39      ng        505: 
1.315     bowersj2  506: # Given the score (as a number [0-1] and the weight) what is the final
                    507: # point value? This function will round to the nearest tenth, third,
                    508: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  509: sub compute_points {
1.315     bowersj2  510:     my ($score, $weight) = @_;
                    511:     
                    512:     my $tolerance = .00001;
                    513:     my $points = $score * $weight;
                    514: 
                    515:     # Check for nearness to 1/x.
                    516:     my $check_for_nearness = sub {
                    517:         my ($factor) = @_;
                    518:         my $num = ($points * $factor) + $tolerance;
                    519:         my $floored_num = floor($num);
1.316     albertel  520:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  521:             return $floored_num / $factor;
                    522:         }
                    523:         return $points;
                    524:     };
                    525: 
                    526:     $points = $check_for_nearness->(10);
                    527:     $points = $check_for_nearness->(3);
                    528:     $points = $check_for_nearness->(4);
                    529:     
                    530:     return $points;
                    531: }
                    532: 
1.44      ng        533: #------------------ End of general use routines --------------------
1.87      www       534: 
                    535: #
                    536: # Find most similar essay
                    537: #
                    538: 
                    539: sub most_similar {
1.426     albertel  540:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       541: 
                    542: # ignore spaces and punctuation
                    543: 
                    544:     $uessay=~s/\W+/ /gs;
                    545: 
1.282     www       546: # ignore empty submissions (occuring when only files are sent)
                    547: 
                    548:     unless ($uessay=~/\w+/) { return ''; }
                    549: 
1.87      www       550: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       551:     my $limit=0.6;
1.87      www       552:     my $sname='';
                    553:     my $sdom='';
                    554:     my $scrsid='';
                    555:     my $sessay='';
                    556: # go through all essays ...
1.426     albertel  557:     foreach my $tkey (keys(%$old_essays)) {
                    558: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       559: # ... except the same student
1.426     albertel  560:         next if (($tname eq $uname) && ($tdom eq $udom));
                    561: 	my $tessay=$old_essays->{$tkey};
                    562: 	$tessay=~s/\W+/ /gs;
1.87      www       563: # String similarity gives up if not even limit
1.426     albertel  564: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       565: # Found one
1.426     albertel  566: 	if ($tsimilar>$limit) {
                    567: 	    $limit=$tsimilar;
                    568: 	    $sname=$tname;
                    569: 	    $sdom=$tdom;
                    570: 	    $scrsid=$tcrsid;
                    571: 	    $sessay=$old_essays->{$tkey};
                    572: 	}
1.87      www       573:     }
1.88      www       574:     if ($limit>0.6) {
1.87      www       575:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    576:     } else {
                    577:        return ('','','','',0);
                    578:     }
                    579: }
                    580: 
1.44      ng        581: #-------------------------------------------------------------------
                    582: 
                    583: #------------------------------------ Receipt Verification Routines
1.45      ng        584: #
1.44      ng        585: #--- Check whether a receipt number is valid.---
                    586: sub verifyreceipt {
                    587:     my $request  = shift;
                    588: 
1.257     albertel  589:     my $courseid = $env{'request.course.id'};
1.184     www       590:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  591: 	$env{'form.receipt'};
1.44      ng        592:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  593:     my ($symb)   = &get_symb($request);
1.44      ng        594: 
1.398     albertel  595:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
                    596: 	$receipt.'</h3></span>'."\n".
                    597: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
1.44      ng        598: 
                    599:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   600:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  601:     
                    602:     my $receiptparts=0;
1.390     albertel  603:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    604: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  605:     my $parts=['0'];
1.324     albertel  606:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.294     albertel  607:     foreach (sort 
                    608: 	     {
                    609: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    610: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    611: 		 }
                    612: 		 return $a cmp $b;
                    613: 	     } (keys(%$fullname))) {
1.44      ng        614: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  615: 	foreach my $part (@$parts) {
                    616: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
                    617: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
                    618: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  619: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  620: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    621: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    622: 		if ($receiptparts) {
                    623: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    624: 		}
                    625: 		$contents.='</tr>'."\n";
                    626: 		
                    627: 		$matches++;
                    628: 	    }
1.44      ng        629: 	}
                    630:     }
                    631:     if ($matches == 0) {
                    632: 	$string = $title.'No match found for the above receipt.';
                    633:     } else {
1.324     albertel  634: 	$string = &jscriptNform($symb).$title.
1.44      ng        635: 	    'The above receipt matches the following student'.
                    636: 	    ($matches <= 1 ? '.' : 's.')."\n".
                    637: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                    638: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
                    639: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
                    640: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
1.177     albertel  641: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
                    642: 	if ($receiptparts) {
                    643: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
                    644: 	}
                    645: 	$string.='</tr>'."\n".$contents.
1.44      ng        646: 	    '</table></td></tr></table>'."\n";
                    647:     }
1.324     albertel  648:     return $string.&show_grading_menu_form($symb);
1.44      ng        649: }
                    650: 
                    651: #--- This is called by a number of programs.
                    652: #--- Called from the Grading Menu - View/Grade an individual student
                    653: #--- Also called directly when one clicks on the subm button 
                    654: #    on the problem page.
1.30      ng        655: sub listStudents {
1.41      ng        656:     my ($request) = shift;
1.49      albertel  657: 
1.324     albertel  658:     my ($symb) = &get_symb($request);
1.257     albertel  659:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    660:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    661:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                    662:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    663: 
                    664:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    665:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    666: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  667: 
1.398     albertel  668:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
                    669: 	' Submissions for a Student or a Group of Students</span></h3>';
1.118     ng        670: 
1.324     albertel  671:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  672: 
1.45      ng        673:     $request->print(<<LISTJAVASCRIPT);
                    674: <script type="text/javascript" language="javascript">
1.110     ng        675:     function checkSelect(checkBox) {
                    676: 	var ctr=0;
                    677: 	var sense="";
                    678: 	if (checkBox.length > 1) {
                    679: 	    for (var i=0; i<checkBox.length; i++) {
                    680: 		if (checkBox[i].checked) {
                    681: 		    ctr++;
                    682: 		}
                    683: 	    }
                    684: 	    sense = "a student or group of students";
                    685: 	} else {
                    686: 	    if (checkBox.checked) {
                    687: 		ctr = 1;
                    688: 	    }
                    689: 	    sense = "the student";
                    690: 	}
                    691: 	if (ctr == 0) {
1.126     ng        692: 	    alert("Please select "+sense+" before clicking on the Next button.");
1.110     ng        693: 	    return false;
                    694: 	}
                    695: 	document.gradesub.submit();
                    696:     }
                    697: 
                    698:     function reLoadList(formname) {
1.112     ng        699: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        700: 	formname.command.value = 'submission';
                    701: 	formname.submit();
                    702:     }
1.45      ng        703: </script>
                    704: LISTJAVASCRIPT
                    705: 
1.118     ng        706:     &commonJSfunctions($request);
1.41      ng        707:     $request->print($result);
1.39      ng        708: 
1.401     albertel  709:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    710:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  711:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
                    712: 	"\n".$table.
1.401     albertel  713: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.267     albertel  714: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
                    715: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
                    716: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
                    717: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
1.401     albertel  718: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
1.49      albertel  719: 	'&nbsp;<b>Submissions: </b>'."\n";
1.257     albertel  720:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.267     albertel  721: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
1.49      albertel  722:     }
1.110     ng        723: 
1.257     albertel  724:     my $saveStatus = $env{'form.Status'} eq '' ? 'Active' : $env{'form.Status'};
                    725:     $env{'form.Status'} = $saveStatus;
1.267     albertel  726:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
                    727: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
                    728: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
1.348     bowersj2  729: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
                    730:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
                    731:         '<option value="1">Whole Points</option>'.
                    732:         '<option value=".5">Half Points</option>'.
1.349     albertel  733:         '<option value=".25">Quarter Points</option>'.
                    734:         '<option value=".1">Tenths of a Point</option>'.
1.348     bowersj2  735:         '</select>'.
1.432   ! banghart  736:         &build_section_inputs().
1.45      ng        737: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  738: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    739: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    740: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    741: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  742: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        743: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    744: 
1.257     albertel  745:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
                    746: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng        747:     } else {
                    748: 	$gradeTable.='<b>Student Status:</b> '.
                    749: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
                    750:     }
1.112     ng        751: 
1.126     ng        752:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    753: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
1.110     ng        754: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  755: 
                    756: # checkall buttons
                    757:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        758:     $gradeTable.='<input type="button" '."\n".
1.45      ng        759: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.249     albertel  760: 	'value="Next->" /> <br />'."\n";
                    761:     $gradeTable.=&check_buttons();
1.401     albertel  762:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
1.249     albertel  763:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
1.45      ng        764:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
1.110     ng        765: 	'<table border="0"><tr bgcolor="#e6ffff">';
                    766:     my $loop = 0;
                    767:     while ($loop < 2) {
1.126     ng        768: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
1.250     albertel  769: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
1.301     albertel  770: 	if ($env{'form.showgrading'} eq 'yes' 
                    771: 	    && $submitonly ne 'queued'
                    772: 	    && $submitonly ne 'all') {
1.110     ng        773: 	    foreach (sort(@$partlist)) {
1.324     albertel  774: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
1.207     albertel  775: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
                    776: 		    ' Status&nbsp;</b></td>';
1.110     ng        777: 	    }
1.301     albertel  778: 	} elsif ($submitonly eq 'queued') {
                    779: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
1.110     ng        780: 	}
                    781: 	$loop++;
1.126     ng        782: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        783:     }
1.45      ng        784:     $gradeTable.='</tr>'."\n";
1.41      ng        785: 
1.45      ng        786:     my $ctr = 0;
1.294     albertel  787:     foreach my $student (sort 
                    788: 			 {
                    789: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    790: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    791: 			     }
                    792: 			     return $a cmp $b;
                    793: 			 }
                    794: 			 (keys(%$fullname))) {
1.41      ng        795: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  796: 
1.110     ng        797: 	my %status = ();
1.301     albertel  798: 
                    799: 	if ($submitonly eq 'queued') {
                    800: 	    my %queue_status = 
                    801: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    802: 							$udom,$uname);
                    803: 	    next if (!defined($queue_status{'gradingqueue'}));
                    804: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    805: 	}
                    806: 
                    807: 	if ($env{'form.showgrading'} eq 'yes' 
                    808: 	    && $submitonly ne 'queued'
                    809: 	    && $submitonly ne 'all') {
1.324     albertel  810: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  811: 	    my $submitted = 0;
1.164     albertel  812: 	    my $graded = 0;
1.248     albertel  813: 	    my $incorrect = 0;
1.110     ng        814: 	    foreach (keys(%status)) {
1.145     albertel  815: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  816: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    817: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    818: 		
1.110     ng        819: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    820: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  821: 		    $submitted = 0;
1.150     albertel  822: 		    my ($part)=split(/\./,$partid);
1.110     ng        823: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  824: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        825: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    826: 		}
1.41      ng        827: 	    }
1.248     albertel  828: 	    
1.156     albertel  829: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    830: 				     $submitonly eq 'incorrect' ||
                    831: 				     $submitonly eq 'graded'));
1.248     albertel  832: 	    next if (!$graded && ($submitonly eq 'graded'));
                    833: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        834: 	}
1.34      ng        835: 
1.45      ng        836: 	$ctr++;
1.249     albertel  837: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    838: 
1.104     albertel  839: 	if ( $perm{'vgr'} eq 'F' ) {
1.110     ng        840: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
1.126     ng        841: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  842:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    843:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    844: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    845: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
                    846: 	       '&nbsp;'.$section.'</td>'."\n";
1.110     ng        847: 
1.257     albertel  848: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        849: 		foreach (sort keys(%status)) {
                    850: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  851: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        852: 		}
1.41      ng        853: 	    }
1.126     ng        854: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.110     ng        855: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
1.41      ng        856: 	}
                    857:     }
1.110     ng        858:     if ($ctr%2 ==1) {
1.126     ng        859: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel  860: 	    if ($env{'form.showgrading'} eq 'yes' 
                    861: 		&& $submitonly ne 'queued'
                    862: 		&& $submitonly ne 'all') {
1.110     ng        863: 		foreach (@$partlist) {
                    864: 		    $gradeTable.='<td>&nbsp;</td>';
                    865: 		}
1.301     albertel  866: 	    } elsif ($submitonly eq 'queued') {
                    867: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng        868: 	    }
                    869: 	$gradeTable.='</tr>';
                    870:     }
                    871: 
1.249     albertel  872:     $gradeTable.='</table></td></tr></table>'."\n".
1.45      ng        873: 	'<input type="button" '.
                    874: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng        875: 	'value="Next->" /></form>'."\n";
1.45      ng        876:     if ($ctr == 0) {
1.96      albertel  877: 	my $num_students=(scalar(keys(%$fullname)));
                    878: 	if ($num_students eq 0) {
1.398     albertel  879: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel  880: 	} else {
1.171     albertel  881: 	    my $submissions='submissions';
                    882: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                    883: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel  884: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel  885: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel  886: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel  887: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel  888: 	}
1.46      ng        889:     } elsif ($ctr == 1) {
                    890: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
1.45      ng        891:     }
1.324     albertel  892:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng        893:     $request->print($gradeTable);
1.44      ng        894:     return '';
1.10      ng        895: }
                    896: 
1.44      ng        897: #---- Called from the listStudents routine
1.249     albertel  898: 
                    899: sub check_script {
                    900:     my ($form, $type)=@_;
                    901:     my $chkallscript='<script type="text/javascript">
                    902:     function checkall() {
                    903:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    904:             ele = document.forms.'.$form.'.elements[i];
                    905:             if (ele.name == "'.$type.'") {
                    906:             document.forms.'.$form.'.elements[i].checked=true;
                    907:                                        }
                    908:         }
                    909:     }
                    910: 
                    911:     function checksec() {
                    912:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    913:             ele = document.forms.'.$form.'.elements[i];
                    914:            string = document.forms.'.$form.'.chksec.value;
                    915:            if
                    916:           (ele.value.indexOf(":::SECTION"+string)>0) {
                    917:               document.forms.'.$form.'.elements[i].checked=true;
                    918:             }
                    919:         }
                    920:     }
                    921: 
                    922: 
                    923:     function uncheckall() {
                    924:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    925:             ele = document.forms.'.$form.'.elements[i];
                    926:             if (ele.name == "'.$type.'") {
                    927:             document.forms.'.$form.'.elements[i].checked=false;
                    928:                                        }
                    929:         }
                    930:     }
                    931: 
                    932: </script>'."\n";
                    933:     return $chkallscript;
                    934: }
                    935: 
                    936: sub check_buttons {
                    937:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                    938:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                    939:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                    940:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                    941:     return $buttons;
                    942: }
                    943: 
1.44      ng        944: #     Displays the submissions for one student or a group of students
1.34      ng        945: sub processGroup {
1.41      ng        946:     my ($request)  = shift;
                    947:     my $ctr        = 0;
1.155     albertel  948:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng        949:     my $total      = scalar(@stuchecked)-1;
1.45      ng        950: 
1.396     banghart  951:     foreach my $student (@stuchecked) {
                    952: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel  953: 	$env{'form.student'}        = $uname;
                    954: 	$env{'form.userdom'}        = $udom;
                    955: 	$env{'form.fullname'}       = $fullname;
1.41      ng        956: 	&submission($request,$ctr,$total);
                    957: 	$ctr++;
                    958:     }
                    959:     return '';
1.35      ng        960: }
1.34      ng        961: 
1.44      ng        962: #------------------------------------------------------------------------------------
                    963: #
                    964: #-------------------------- Next few routines handles grading by student, essentially
                    965: #                           handles essay response type problem/part
                    966: #
                    967: #--- Javascript to handle the submission page functionality ---
                    968: sub sub_page_js {
                    969:     my $request = shift;
                    970:     $request->print(<<SUBJAVASCRIPT);
                    971: <script type="text/javascript" language="javascript">
1.71      ng        972:     function updateRadio(formname,id,weight) {
1.125     ng        973: 	var gradeBox = formname["GD_BOX"+id];
                    974: 	var radioButton = formname["RADVAL"+id];
                    975: 	var oldpts = formname["oldpts"+id].value;
1.72      ng        976: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng        977: 	gradeBox.value = pts;
                    978: 	var resetbox = false;
                    979: 	if (isNaN(pts) || pts < 0) {
                    980: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                    981: 	    for (var i=0; i<radioButton.length; i++) {
                    982: 		if (radioButton[i].checked) {
                    983: 		    gradeBox.value = i;
                    984: 		    resetbox = true;
                    985: 		}
                    986: 	    }
                    987: 	    if (!resetbox) {
                    988: 		formtextbox.value = "";
                    989: 	    }
                    990: 	    return;
1.44      ng        991: 	}
1.71      ng        992: 
                    993: 	if (pts > weight) {
                    994: 	    var resp = confirm("You entered a value ("+pts+
                    995: 			       ") greater than the weight for the part. Accept?");
                    996: 	    if (resp == false) {
1.125     ng        997: 		gradeBox.value = oldpts;
1.71      ng        998: 		return;
                    999: 	    }
1.44      ng       1000: 	}
1.13      albertel 1001: 
1.71      ng       1002: 	for (var i=0; i<radioButton.length; i++) {
                   1003: 	    radioButton[i].checked=false;
                   1004: 	    if (pts == i && pts != "") {
                   1005: 		radioButton[i].checked=true;
                   1006: 	    }
                   1007: 	}
                   1008: 	updateSelect(formname,id);
1.125     ng       1009: 	formname["stores"+id].value = "0";
1.41      ng       1010:     }
1.5       albertel 1011: 
1.72      ng       1012:     function writeBox(formname,id,pts) {
1.125     ng       1013: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1014: 	if (checkSolved(formname,id) == 'update') {
                   1015: 	    gradeBox.value = pts;
                   1016: 	} else {
1.125     ng       1017: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1018: 	    gradeBox.value = oldpts;
1.125     ng       1019: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1020: 	    for (var i=0; i<radioButton.length; i++) {
                   1021: 		radioButton[i].checked=false;
1.72      ng       1022: 		if (i == oldpts) {
1.71      ng       1023: 		    radioButton[i].checked=true;
                   1024: 		}
                   1025: 	    }
1.41      ng       1026: 	}
1.125     ng       1027: 	formname["stores"+id].value = "0";
1.71      ng       1028: 	updateSelect(formname,id);
                   1029: 	return;
1.41      ng       1030:     }
1.44      ng       1031: 
1.71      ng       1032:     function clearRadBox(formname,id) {
                   1033: 	if (checkSolved(formname,id) == 'noupdate') {
                   1034: 	    updateSelect(formname,id);
                   1035: 	    return;
                   1036: 	}
1.125     ng       1037: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1038: 	for (var i=0; i<gradeSelect.length; i++) {
                   1039: 	    if (gradeSelect[i].selected) {
                   1040: 		var selectx=i;
                   1041: 	    }
                   1042: 	}
1.125     ng       1043: 	var stores = formname["stores"+id];
1.71      ng       1044: 	if (selectx == stores.value) { return };
1.125     ng       1045: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1046: 	gradeBox.value = "";
1.125     ng       1047: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1048: 	for (var i=0; i<radioButton.length; i++) {
                   1049: 	    radioButton[i].checked=false;
                   1050: 	}
                   1051: 	stores.value = selectx;
                   1052:     }
1.5       albertel 1053: 
1.71      ng       1054:     function checkSolved(formname,id) {
1.125     ng       1055: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1056: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1057: 	    if (!reply) {return "noupdate";}
1.120     ng       1058: 	    formname.overRideScore.value = 'yes';
1.41      ng       1059: 	}
1.71      ng       1060: 	return "update";
1.13      albertel 1061:     }
1.71      ng       1062: 
                   1063:     function updateSelect(formname,id) {
1.125     ng       1064: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1065: 	return;
1.41      ng       1066:     }
1.33      ng       1067: 
1.121     ng       1068: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1069:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1070: 	formname.gradeOpt.value = val;
1.71      ng       1071: 	if (val == "Save & Next") {
                   1072: 	    for (i=0;i<=total;i++) {
                   1073: 		for (j=0;j<parttot;j++) {
1.125     ng       1074: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1075: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1076: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1077: 			if (points == "") {
1.125     ng       1078: 			    var name = formname["name"+i].value;
1.129     ng       1079: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1080: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1081: 					       ", part "+partid+". Continue?");
1.71      ng       1082: 			    if (resp == false) {
1.125     ng       1083: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1084: 				return false;
                   1085: 			    }
                   1086: 			}
                   1087: 		    }
                   1088: 		    
                   1089: 		}
                   1090: 	    }
                   1091: 	    
                   1092: 	}
1.121     ng       1093: 	if (val == "Grade Student") {
                   1094: 	    formname.showgrading.value = "yes";
                   1095: 	    if (formname.Status.value == "") {
                   1096: 		formname.Status.value = "Active";
                   1097: 	    }
                   1098: 	    formname.studentNo.value = total;
                   1099: 	}
1.120     ng       1100: 	formname.submit();
                   1101:     }
                   1102: 
1.71      ng       1103: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1104:     function checkSubmitPage(formname,total) {
                   1105: 	noscore = new Array(100);
                   1106: 	var ptr = 0;
                   1107: 	for (i=1;i<total;i++) {
1.125     ng       1108: 	    var partid = formname["q_"+i].value;
1.127     ng       1109: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1110: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1111: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1112: 		if (points == "" && status != "correct_by_student") {
                   1113: 		    noscore[ptr] = i;
                   1114: 		    ptr++;
                   1115: 		}
                   1116: 	    }
                   1117: 	}
                   1118: 	if (ptr != 0) {
                   1119: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1120: 	    var prolist = "";
                   1121: 	    if (ptr == 1) {
                   1122: 		prolist = noscore[0];
                   1123: 	    } else {
                   1124: 		var i = 0;
                   1125: 		while (i < ptr-1) {
                   1126: 		    prolist += noscore[i]+", ";
                   1127: 		    i++;
                   1128: 		}
                   1129: 		prolist += "and "+noscore[i];
                   1130: 	    }
                   1131: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1132: 	    if (resp == false) {
                   1133: 		return false;
                   1134: 	    }
                   1135: 	}
1.45      ng       1136: 
1.71      ng       1137: 	formname.submit();
                   1138:     }
                   1139: </script>
                   1140: SUBJAVASCRIPT
                   1141: }
1.45      ng       1142: 
1.71      ng       1143: #--- javascript for essay type problem --
                   1144: sub sub_page_kw_js {
                   1145:     my $request = shift;
1.80      ng       1146:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1147:     &commonJSfunctions($request);
1.350     albertel 1148: 
1.351     albertel 1149:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1150:     <script text="text/javascript">
                   1151:     function checkInput() {
                   1152:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1153:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1154:       var usrctr = document.msgcenter.usrctr.value;
                   1155:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1156:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1157: 
                   1158:       var msgchk = "";
                   1159:       if (document.msgcenter.subchk.checked) {
                   1160:          msgchk = "msgsub,";
                   1161:       }
                   1162:       var includemsg = 0;
                   1163:       for (var i=1; i<=nmsg; i++) {
                   1164:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1165:           var frmmsg = document.msgcenter["msg"+i];
                   1166:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1167:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1168:           showflg.value = "1";
                   1169:           var chkbox = document.msgcenter["msgn"+i];
                   1170:           if (chkbox.checked) {
                   1171:              msgchk += "savemsg"+i+",";
                   1172:              includemsg = 1;
                   1173:           }
                   1174:       }
                   1175:       if (document.msgcenter.newmsgchk.checked) {
                   1176:          msgchk += "newmsg"+usrctr;
                   1177:          includemsg = 1;
                   1178:       }
                   1179:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1180:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1181:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1182:       includemsg.value = msgchk;
                   1183: 
                   1184:       self.close()
                   1185: 
                   1186:     }
                   1187:     </script>
                   1188: INNERJS
                   1189: 
1.351     albertel 1190:     my $inner_js_highlight_central=<<INNERJS;
                   1191:  <script type="text/javascript">
                   1192:     function updateChoice(flag) {
                   1193:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1194:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1195:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1196:       opener.document.SCORE.refresh.value = "on";
                   1197:       if (opener.document.SCORE.keywords.value!=""){
                   1198:          opener.document.SCORE.submit();
                   1199:       }
                   1200:       self.close()
                   1201:     }
                   1202: </script>
                   1203: INNERJS
                   1204: 
                   1205:     my $start_page_msg_central = 
                   1206:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1207: 				       {'js_ready'  => 1,
                   1208: 					'only_body' => 1,
                   1209: 					'bgcolor'   =>'#FFFFFF',});
                   1210:     my $end_page_msg_central = 
                   1211: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1212: 
                   1213: 
                   1214:     my $start_page_highlight_central = 
                   1215:         &Apache::loncommon::start_page('Highlight Central',
                   1216: 				       $inner_js_highlight_central,
1.350     albertel 1217: 				       {'js_ready'  => 1,
                   1218: 					'only_body' => 1,
                   1219: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1220:     my $end_page_highlight_central = 
1.350     albertel 1221: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1222: 
1.219     www      1223:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1224:     $docopen=~s/^document\.//;
1.71      ng       1225:     $request->print(<<SUBJAVASCRIPT);
                   1226: <script type="text/javascript" language="javascript">
1.45      ng       1227: 
1.44      ng       1228: //===================== Show list of keywords ====================
1.122     ng       1229:   function keywords(formname) {
                   1230:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1231:     if (nret==null) return;
1.122     ng       1232:     formname.keywords.value = nret;
1.44      ng       1233: 
1.122     ng       1234:     if (formname.keywords.value != "") {
1.128     ng       1235: 	formname.refresh.value = "on";
1.122     ng       1236: 	formname.submit();
1.44      ng       1237:     }
                   1238:     return;
                   1239:   }
                   1240: 
                   1241: //===================== Script to view submitted by ==================
                   1242:   function viewSubmitter(submitter) {
                   1243:     document.SCORE.refresh.value = "on";
                   1244:     document.SCORE.NCT.value = "1";
                   1245:     document.SCORE.unamedom0.value = submitter;
                   1246:     document.SCORE.submit();
                   1247:     return;
                   1248:   }
                   1249: 
                   1250: //===================== Script to add keyword(s) ==================
                   1251:   function getSel() {
                   1252:     if (document.getSelection) txt = document.getSelection();
                   1253:     else if (document.selection) txt = document.selection.createRange().text;
                   1254:     else return;
                   1255:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1256:     if (cleantxt=="") {
1.46      ng       1257: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1258: 	return;
                   1259:     }
                   1260:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1261:     if (nret==null) return;
1.127     ng       1262:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1263:     if (document.SCORE.keywords.value != "") {
1.127     ng       1264: 	document.SCORE.refresh.value = "on";
1.44      ng       1265: 	document.SCORE.submit();
                   1266:     }
                   1267:     return;
                   1268:   }
                   1269: 
                   1270: //====================== Script for composing message ==============
1.80      ng       1271:    // preload images
                   1272:    img1 = new Image();
                   1273:    img1.src = "$iconpath/mailbkgrd.gif";
                   1274:    img2 = new Image();
                   1275:    img2.src = "$iconpath/mailto.gif";
                   1276: 
1.44      ng       1277:   function msgCenter(msgform,usrctr,fullname) {
                   1278:     var Nmsg  = msgform.savemsgN.value;
                   1279:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1280:     var subject = msgform.msgsub.value;
1.127     ng       1281:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1282:     re = /msgsub/;
                   1283:     var shwsel = "";
                   1284:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1285:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1286:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1287:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1288: 	var testmsg = "savemsg"+i+",";
                   1289: 	re = new RegExp(testmsg,"g");
1.44      ng       1290: 	shwsel = "";
                   1291: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1292: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1293: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1294: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1295: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1296:     }
1.125     ng       1297:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1298:     shwsel = "";
                   1299:     re = /newmsg/;
                   1300:     if (re.test(msgchk)) { shwsel = "checked" }
                   1301:     newMsg(newmsg,shwsel);
                   1302:     msgTail(); 
                   1303:     return;
                   1304:   }
                   1305: 
1.123     ng       1306:   function checkEntities(strx) {
                   1307:     if (strx.length == 0) return strx;
                   1308:     var orgStr = ["&", "<", ">", '"']; 
                   1309:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1310:     var counter = 0;
                   1311:     while (counter < 4) {
                   1312: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1313: 	counter++;
                   1314:     }
                   1315:     return strx;
                   1316:   }
                   1317: 
                   1318:   function strReplace(strx, orgStr, newStr) {
                   1319:     return strx.split(orgStr).join(newStr);
                   1320:   }
                   1321: 
1.44      ng       1322:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1323:     var height = 70*Nmsg+250;
1.44      ng       1324:     var scrollbar = "no";
                   1325:     if (height > 600) {
                   1326: 	height = 600;
                   1327: 	scrollbar = "yes";
                   1328:     }
1.118     ng       1329:     var xpos = (screen.width-600)/2;
                   1330:     xpos = (xpos < 0) ? '0' : xpos;
                   1331:     var ypos = (screen.height-height)/2-30;
                   1332:     ypos = (ypos < 0) ? '0' : ypos;
                   1333: 
1.206     albertel 1334:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1335:     pWin.focus();
                   1336:     pDoc = pWin.document;
1.219     www      1337:     pDoc.$docopen;
1.351     albertel 1338:     pDoc.write('$start_page_msg_central');
1.76      ng       1339: 
                   1340:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1341:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.398     albertel 1342:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
1.76      ng       1343: 
                   1344:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1345:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1346:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1.44      ng       1347: }
                   1348:     function displaySubject(msg,shwsel) {
1.76      ng       1349:     pDoc = pWin.document;
                   1350:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1351:     pDoc.write("<td>Subject</td>");
                   1352:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1353:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1.44      ng       1354: }
                   1355: 
1.72      ng       1356:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1357:     pDoc = pWin.document;
                   1358:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1359:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
                   1360:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1361:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1.44      ng       1362: }
                   1363: 
                   1364:   function newMsg(newmsg,shwsel) {
1.76      ng       1365:     pDoc = pWin.document;
                   1366:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1367:     pDoc.write("<td align=\\"center\\">New</td>");
                   1368:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1369:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1.44      ng       1370: }
                   1371: 
                   1372:   function msgTail() {
1.76      ng       1373:     pDoc = pWin.document;
                   1374:     pDoc.write("</table>");
                   1375:     pDoc.write("</td></tr></table>&nbsp;");
                   1376:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1377:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1378:     pDoc.write("</form>");
1.351     albertel 1379:     pDoc.write('$end_page_msg_central');
1.128     ng       1380:     pDoc.close();
1.44      ng       1381: }
                   1382: 
                   1383: //====================== Script for keyword highlight options ==============
                   1384:   function kwhighlight() {
                   1385:     var kwclr    = document.SCORE.kwclr.value;
                   1386:     var kwsize   = document.SCORE.kwsize.value;
                   1387:     var kwstyle  = document.SCORE.kwstyle.value;
                   1388:     var redsel = "";
                   1389:     var grnsel = "";
                   1390:     var blusel = "";
                   1391:     if (kwclr=="red")   {var redsel="checked"};
                   1392:     if (kwclr=="green") {var grnsel="checked"};
                   1393:     if (kwclr=="blue")  {var blusel="checked"};
                   1394:     var sznsel = "";
                   1395:     var sz1sel = "";
                   1396:     var sz2sel = "";
                   1397:     if (kwsize=="0")  {var sznsel="checked"};
                   1398:     if (kwsize=="+1") {var sz1sel="checked"};
                   1399:     if (kwsize=="+2") {var sz2sel="checked"};
                   1400:     var synsel = "";
                   1401:     var syisel = "";
                   1402:     var sybsel = "";
                   1403:     if (kwstyle=="")    {var synsel="checked"};
                   1404:     if (kwstyle=="<i>") {var syisel="checked"};
                   1405:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1406:     highlightCentral();
                   1407:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1408:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1409:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1410:     highlightend();
                   1411:     return;
                   1412:   }
                   1413: 
                   1414:   function highlightCentral() {
1.76      ng       1415: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1416:     var xpos = (screen.width-400)/2;
                   1417:     xpos = (xpos < 0) ? '0' : xpos;
                   1418:     var ypos = (screen.height-330)/2-30;
                   1419:     ypos = (ypos < 0) ? '0' : ypos;
                   1420: 
1.206     albertel 1421:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1422:     hwdWin.focus();
                   1423:     var hDoc = hwdWin.document;
1.219     www      1424:     hDoc.$docopen;
1.351     albertel 1425:     hDoc.write('$start_page_highlight_central');
1.76      ng       1426:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.398     albertel 1427:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
1.76      ng       1428: 
                   1429:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1430:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1431:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1.44      ng       1432:   }
                   1433: 
                   1434:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1435:     var hDoc = hwdWin.document;
                   1436:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1437:     hDoc.write("<td align=\\"left\\">");
                   1438:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
                   1439:     hDoc.write("<td align=\\"left\\">");
                   1440:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
                   1441:     hDoc.write("<td align=\\"left\\">");
                   1442:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
                   1443:     hDoc.write("</tr>");
1.44      ng       1444:   }
                   1445: 
                   1446:   function highlightend() { 
1.76      ng       1447:     var hDoc = hwdWin.document;
                   1448:     hDoc.write("</table>");
                   1449:     hDoc.write("</td></tr></table>&nbsp;");
                   1450:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1451:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1452:     hDoc.write("</form>");
1.351     albertel 1453:     hDoc.write('$end_page_highlight_central');
1.128     ng       1454:     hDoc.close();
1.44      ng       1455:   }
                   1456: 
                   1457: </script>
                   1458: SUBJAVASCRIPT
                   1459: }
                   1460: 
1.349     albertel 1461: sub get_increment {
1.348     bowersj2 1462:     my $increment = $env{'form.increment'};
                   1463:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1464:         $increment != .1) {
                   1465:         $increment = 1;
                   1466:     }
                   1467:     return $increment;
                   1468: }
                   1469: 
1.71      ng       1470: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1471: sub gradeBox {
1.322     albertel 1472:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1473:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1474: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1475: 	'/check.gif" height="16" border="0" />';
                   1476:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
                   1477:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
1.398     albertel 1478: 		  '<span class="LC_info">problem weight assigned by computer</span>');
1.71      ng       1479:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1480:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1481: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1482:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.324     albertel 1483:     my $display_part=&get_display_part($partid,$symb);
1.270     albertel 1484:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1485: 				       [$partid]);
                   1486:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1487:     if ($last_resets{$partid}) {
                   1488:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1489:     }
1.71      ng       1490:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1491: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1492:     my $ctr = 0;
1.348     bowersj2 1493:     my $thisweight = 0;
1.349     albertel 1494:     my $increment = &get_increment();
1.71      ng       1495:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1496:     while ($thisweight<=$wgt) {
1.381     albertel 1497: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1498: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1499: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1500: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1501: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1502:         $thisweight += $increment;
1.71      ng       1503: 	$ctr++;
                   1504:     }
                   1505:     $result.='</tr></table>';
                   1506:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1507:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1508: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1509: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1510: 	$wgt.')" /></td>'."\n";
                   1511:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1512: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1513: 	' </td><td>'."\n";
                   1514:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1515: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1516:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1517: 	$result.='<option></option>'.
1.401     albertel 1518: 	    '<option selected="selected">excused</option>';
1.71      ng       1519:     } else {
1.401     albertel 1520: 	$result.='<option selected="selected"></option>'.
1.125     ng       1521: 	    '<option>excused</option>';
1.71      ng       1522:     }
1.125     ng       1523:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1524:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1525:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1526: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1527: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1528: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1529:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1530:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1531:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1532:         $aggtries.'" />'."\n";
1.71      ng       1533:     $result.='</td></tr></table>'."\n";
1.323     banghart 1534:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1535:     return $result;
                   1536: }
1.322     albertel 1537: 
                   1538: sub handback_box {
1.323     banghart 1539:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1540:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1541:     my (@respids);
1.375     albertel 1542:      my @part_response_id = &flatten_responseType($responseType);
                   1543:     foreach my $part_response_id (@part_response_id) {
                   1544:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1545:         if ($part eq $partid) {
1.375     albertel 1546:             push(@respids,$resp);
1.323     banghart 1547:         }
                   1548:     }
1.318     banghart 1549:     my $result;
1.323     banghart 1550:     foreach my $respid (@respids) {
1.322     albertel 1551: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1552: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1553: 	next if (!@$files);
                   1554: 	my $file_counter = 1;
1.313     banghart 1555: 	foreach my $file (@$files) {
1.368     banghart 1556: 	    if ($file =~ /\/portfolio\//) {
                   1557:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1558:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1559:     	        $file_disp = "$name.$ext";
                   1560:     	        $file = $file_path.$file_disp;
                   1561:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1562:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1563:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1564:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.369     banghart 1565:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1.368     banghart 1566:     	        $file_counter++;
                   1567: 	    }
1.322     albertel 1568: 	}
1.313     banghart 1569:     }
1.318     banghart 1570:     return $result;    
1.71      ng       1571: }
1.44      ng       1572: 
1.58      albertel 1573: sub show_problem {
1.382     albertel 1574:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1575:     my $rendered;
1.382     albertel 1576:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1577:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1578:     if ($mode eq 'both' or $mode eq 'text') {
                   1579: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1580: 						       $env{'request.course.id'},
                   1581: 						       undef,\%form);
1.144     albertel 1582:     }
1.58      albertel 1583:     if ($removeform) {
                   1584: 	$rendered=~s|<form(.*?)>||g;
                   1585: 	$rendered=~s|</form>||g;
1.374     albertel 1586: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1587:     }
1.144     albertel 1588:     my $companswer;
                   1589:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1590: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1591: 	$companswer=
                   1592: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1593: 						    $env{'request.course.id'},
                   1594: 						    %form);
1.144     albertel 1595:     }
1.58      albertel 1596:     if ($removeform) {
                   1597: 	$companswer=~s|<form(.*?)>||g;
                   1598: 	$companswer=~s|</form>||g;
1.144     albertel 1599: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1600:     }
                   1601:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1602:     $result.='<table border="0" width="100%">';
1.144     albertel 1603:     if ($viewon) {
                   1604: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1605: 	if ($mode eq 'both' or $mode eq 'text') {
                   1606: 	    $result.='View of the problem - ';
                   1607: 	} else {
                   1608: 	    $result.='Correct answer: ';
                   1609: 	}
1.257     albertel 1610: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1611:     }
                   1612:     if ($mode eq 'both') {
                   1613: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1614: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1615:     } elsif ($mode eq 'text') {
                   1616: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1617:     } elsif ($mode eq 'answer') {
                   1618: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1619:     }
1.58      albertel 1620:     $result.='</td></tr></table>';
                   1621:     $result.='</td></tr></table><br />';
1.71      ng       1622:     return $result;
1.58      albertel 1623: }
1.397     albertel 1624: 
1.396     banghart 1625: sub files_exist {
                   1626:     my ($r, $symb) = @_;
                   1627:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1628: 
1.396     banghart 1629:     foreach my $student (@students) {
                   1630:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1631:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1632: 					      $udom,$uname);
1.396     banghart 1633:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1634:         foreach my $submission (@$string) {
                   1635:             my ($partid,$respid) =
                   1636: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1637:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1638: 					   \%record);
                   1639:             return 1 if (@$files);
1.396     banghart 1640:         }
                   1641:     }
1.397     albertel 1642:     return 0;
1.396     banghart 1643: }
1.397     albertel 1644: 
1.394     banghart 1645: sub download_all_link {
                   1646:     my ($r,$symb) = @_;
1.395     albertel 1647:     my $all_students = 
                   1648: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1649: 
                   1650:     my $parts =
                   1651: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1652: 
1.394     banghart 1653:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1654:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1655:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1656:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1657:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1658: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1659:     return
                   1660: }
1.395     albertel 1661: 
1.432   ! banghart 1662: sub build_section_inputs {
        !          1663:     my $section_inputs;
        !          1664:     if ($env{'form.section'} eq '') {
        !          1665:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
        !          1666:     } else {
        !          1667:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
        !          1668:         foreach my $section(@sections) {
        !          1669:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
        !          1670:         }
        !          1671:     }
        !          1672:     return $section_inputs;
        !          1673: }
        !          1674: 
1.44      ng       1675: # --------------------------- show submissions of a student, option to grade 
                   1676: sub submission {
                   1677:     my ($request,$counter,$total) = @_;
                   1678: 
1.257     albertel 1679:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1680:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1681:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1682:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.41      ng       1683: 
1.324     albertel 1684:     my $symb = &get_symb($request); 
                   1685:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1686: 
                   1687:     if (!&canview($usec)) {
1.398     albertel 1688: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1689: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1690: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1691: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1692: 	return;
                   1693:     }
                   1694: 
1.257     albertel 1695:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1696:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1697:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1698:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1699:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1700: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1701: 	'/check.gif" height="16" border="0" />';
1.41      ng       1702: 
1.426     albertel 1703:     my %old_essays;
1.41      ng       1704:     # header info
                   1705:     if ($counter == 0) {
                   1706: 	&sub_page_js($request);
1.257     albertel 1707: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1708: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1709: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1710: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1711: 	    &download_all_link($request, $symb);
                   1712: 	}
1.398     albertel 1713: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
                   1714: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1.118     ng       1715: 
1.257     albertel 1716: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1717: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1718: 		$checkIcon.' symbol.'."\n";
                   1719: 	    $request->print($checkMark);
                   1720: 	}
1.41      ng       1721: 
1.44      ng       1722: 	# option to display problem, only once else it cause problems 
                   1723:         # with the form later since the problem has a form.
1.257     albertel 1724: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1725: 	    my $mode;
1.257     albertel 1726: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1727: 		$mode='both';
1.257     albertel 1728: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1729: 		$mode='text';
1.257     albertel 1730: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1731: 		$mode='answer';
                   1732: 	    }
1.329     albertel 1733: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1734: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1735: 	}
                   1736: 	
1.44      ng       1737: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1738:         # if this subroutine has been called once.
1.41      ng       1739: 	my %keyhash = ();
1.257     albertel 1740: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1741: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1742: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1743: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1744: 
1.257     albertel 1745: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1746: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1747: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1748: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1749: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1750: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1751: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1752: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1753: 	}
1.257     albertel 1754: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.303     banghart 1755: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1756: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1757: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
                   1758: 			'<input type="hidden" name="Status"     value="'.$env{'form.Status'}.'" />'."\n".
1.120     ng       1759: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1760: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1761: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1762: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1763: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1764: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1765: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1766: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1767: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1768: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432   ! banghart 1769: 			&build_section_inputs().
1.326     albertel 1770: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1771: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1772: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1773: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1774: 	if ($env{'form.handgrade'} eq 'yes') {
                   1775: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1776: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1777: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1778: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1779: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1780: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1781: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1782: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1783: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1784: 	    }
1.123     ng       1785: 	}
1.41      ng       1786: 	
                   1787: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1788: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1789: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1790: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1791: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1792: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1793: 		'" />'."\n".
                   1794: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1795: 	    $cts++;
                   1796: 	}
                   1797: 	$request->print($prnmsg);
1.32      ng       1798: 
1.257     albertel 1799: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1800: #
                   1801: # Print out the keyword options line
                   1802: #
1.41      ng       1803: 	    $request->print(<<KEYWORDS);
1.38      ng       1804: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1805: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1806: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1807:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1808: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1809: KEYWORDS
1.88      www      1810: #
                   1811: # Load the other essays for similarity check
                   1812: #
1.324     albertel 1813:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1814: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1815: 	    $apath=&escape($apath);
1.88      www      1816: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1817: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1818:         }
                   1819:     }
1.44      ng       1820: 
1.257     albertel 1821:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.71      ng       1822: 	$request->print('<br /><br /><br />') if ($counter > 0);
1.144     albertel 1823: 	my $mode;
1.257     albertel 1824: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1825: 	    $mode='both';
1.257     albertel 1826: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1827: 	    $mode='text';
1.257     albertel 1828: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1829: 	    $mode='answer';
                   1830: 	}
1.329     albertel 1831: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1832: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1833:     }
1.144     albertel 1834: 
1.257     albertel 1835:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1836:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1837: 
1.44      ng       1838:     # Display student info
1.41      ng       1839:     $request->print(($counter == 0 ? '' : '<br />'));
1.326     albertel 1840:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
                   1841: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1.44      ng       1842: 
1.257     albertel 1843:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1.45      ng       1844:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1845: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1846: 
1.118     ng       1847:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.45      ng       1848:     my @col_fullnames;
1.56      matthew  1849:     my ($classlist,$fullname);
1.257     albertel 1850:     if ($env{'form.handgrade'} eq 'yes') {
1.80      ng       1851: 	($classlist,undef,$fullname) = &getclasslist('all','0');
1.41      ng       1852: 	for (keys (%$handgrade)) {
1.44      ng       1853: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1.57      matthew  1854: 					    '.maxcollaborators',
                   1855:                                             $symb,$udom,$uname);
                   1856: 	    next if ($ncol <= 0);
                   1857:             s/\_/\./g;
                   1858:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
1.86      ng       1859:             my @goodcollaborators = ();
                   1860:             my @badcollaborators  = ();
                   1861: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
                   1862: 		$_ =~ s/[\$\^\(\)]//g;
                   1863: 		next if ($_ eq '');
1.80      ng       1864: 		my ($co_name,$co_dom) = split /\@|:/,$_;
1.86      ng       1865: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1.80      ng       1866: 		next if ($co_name eq $uname && $co_dom eq $udom);
1.86      ng       1867: 		# Doing this grep allows 'fuzzy' specification
                   1868: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
                   1869: 		if (! scalar(@Matches)) {
                   1870: 		    push @badcollaborators,$_;
                   1871: 		} else {
                   1872: 		    push @goodcollaborators, @Matches;
                   1873: 		}
1.80      ng       1874: 	    }
1.86      ng       1875:             if (scalar(@goodcollaborators) != 0) {
1.57      matthew  1876:                 $result.='<b>Collaborators: </b>';
1.86      ng       1877:                 foreach (@goodcollaborators) {
                   1878: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
                   1879: 		    push @col_fullnames, $givenn.' '.$lastname;
                   1880: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
                   1881: 		}
1.57      matthew  1882:                 $result.='<br />'."\n";
1.150     albertel 1883: 		my ($part)=split(/\./,$_);
1.86      ng       1884: 		$result.='<input type="hidden" name="collaborator'.$counter.
1.150     albertel 1885: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
                   1886: 		    "\n";
1.86      ng       1887: 	    }
                   1888: 	    if (scalar(@badcollaborators) > 0) {
                   1889: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1890: 		$result.='This student has submitted ';
                   1891: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
                   1892: 		$result .= ': '.join(', ',@badcollaborators);
                   1893: 		$result .= '</td></tr></table>';
                   1894: 	    }         
                   1895: 	    if (scalar(@badcollaborators > $ncol)) {
                   1896: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1897: 		$result .= 'This student has submitted too many '.
                   1898: 		    'collaborators.  Maximum is '.$ncol.'.';
                   1899: 		$result .= '</td></tr></table>';
                   1900: 	    }
1.41      ng       1901: 	}
                   1902:     }
1.44      ng       1903:     $request->print($result."\n");
1.33      ng       1904: 
1.44      ng       1905:     # print student answer/submission
                   1906:     # Options are (1) Handgaded submission only
                   1907:     #             (2) Last submission, includes submission that is not handgraded 
                   1908:     #                  (for multi-response type part)
                   1909:     #             (3) Last submission plus the parts info
                   1910:     #             (4) The whole record for this student
1.257     albertel 1911:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 1912: 	my ($string,$timestamp)= &get_last_submission(\%record);
                   1913: 	my $lastsubonly=''.
                   1914: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
                   1915: 	     $$timestamp)."</td></tr>\n";
                   1916: 	if ($$timestamp eq '') {
                   1917: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
                   1918: 	} else {
                   1919: 	    my %seenparts;
1.375     albertel 1920: 	    my @part_response_id = &flatten_responseType($responseType);
                   1921: 	    foreach my $part (@part_response_id) {
1.393     albertel 1922: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   1923: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   1924: 
1.375     albertel 1925: 		my ($partid,$respid) = @{ $part };
1.324     albertel 1926: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 1927: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 1928: 		    if (exists($seenparts{$partid})) { next; }
                   1929: 		    $seenparts{$partid}=1;
1.207     albertel 1930: 		    my $submitby='<b>Part:</b> '.$display_part.
                   1931: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 1932: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 1933: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 1934: 			'\');" target="_self">'.
1.257     albertel 1935: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 1936: 		    $request->print($submitby);
                   1937: 		    next;
                   1938: 		}
                   1939: 		my $responsetype = $responseType->{$partid}->{$respid};
                   1940: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.207     albertel 1941: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1.398     albertel 1942: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   1943: 			' )</span>&nbsp; &nbsp;'.
                   1944: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1.151     albertel 1945: 		    next;
                   1946: 		}
                   1947: 		foreach (@$string) {
                   1948: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1.375     albertel 1949: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.151     albertel 1950: 		    my ($ressub,$subval) = split(/:/,$_,2);
                   1951: 		    # Similarity check
                   1952: 		    my $similar='';
1.257     albertel 1953: 		    if($env{'form.checkPlag'}){
1.151     albertel 1954: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 1955: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 1956: 			if ($osim) {
                   1957: 			    $osim=int($osim*100.0);
1.426     albertel 1958: 			    my %old_course_desc = 
                   1959: 				&Apache::lonnet::coursedescription($ocrsid,
                   1960: 								   {'one_time' => 1});
                   1961: 
                   1962: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 1963: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 1964: 				    $osim,
                   1965: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 1966: 				    $oname,$odom,
1.426     albertel 1967: 				    $old_course_desc{'description'},
1.427     albertel 1968: 				    $old_course_desc{'num'},
1.426     albertel 1969: 				    $old_course_desc{'domain'}).
1.398     albertel 1970: 				'</span></h3><blockquote><i>'.
1.151     albertel 1971: 				&keywords_highlight($oessay).
                   1972: 				'</i></blockquote><hr />';
                   1973: 			}
1.150     albertel 1974: 		    }
1.151     albertel 1975: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 1976: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   1977: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 1978: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 1979: 			my $display_part=&get_display_part($partid,$symb);
1.403     albertel 1980: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   1981: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 1982: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 1983: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   1984: 			if (@$files) {
1.398     albertel 1985: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1.303     banghart 1986: 			    my $file_counter = 0;
1.313     banghart 1987: 			    foreach my $file (@$files) {
1.303     banghart 1988: 			        $file_counter ++;
1.232     albertel 1989: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 1990: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 1991: 			    }
1.236     albertel 1992: 			    $lastsubonly.='<br />';
1.41      ng       1993: 			}
1.151     albertel 1994: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   1995: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   1996: 					 $respid,\%record,$order);
                   1997: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       1998: 		    }
                   1999: 		}
                   2000: 	    }
1.151     albertel 2001: 	}
                   2002: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   2003: 	$request->print($lastsubonly);
1.257     albertel 2004:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2005: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2006: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2007:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2008: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2009: 								 $env{'request.course.id'},
1.44      ng       2010: 								 $last,'.submission',
                   2011: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2012:     }
1.120     ng       2013: 
1.121     ng       2014:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2015: 	.$udom.'" />'."\n");
1.41      ng       2016:     
1.44      ng       2017:     # return if view submission with no grading option
1.257     albertel 2018:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2019: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2020: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2021: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 2022: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 2023: 	if (($env{'form.command'} eq 'submission') || 
                   2024: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2025: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2026: 	}
1.180     albertel 2027: 	$request->print($toGrade);
1.41      ng       2028: 	return;
1.180     albertel 2029:     } else {
                   2030: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       2031:     }
1.33      ng       2032: 
1.121     ng       2033:     # essay grading message center
1.257     albertel 2034:     if ($env{'form.handgrade'} eq 'yes') {
                   2035: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2036: 	my $msgfor = $givenn.' '.$lastname;
                   2037: 	if (scalar(@col_fullnames) > 0) {
                   2038: 	    my $lastone = pop @col_fullnames;
                   2039: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   2040: 	}
                   2041: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       2042: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2043: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2044: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2045: 	    ',\''.$msgfor.'\');" target="_self">'.
1.350     albertel 2046: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
                   2047: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2048: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2049: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2050: 	    '<br />&nbsp;('.
                   2051: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       2052: 	$request->print($result);
1.118     ng       2053:     }
1.300     albertel 2054:     if ($perm{'vgr'}) {
1.297     www      2055: 	$request->print('<br />'.
1.300     albertel 2056: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2057: 						   $uname,$udom,'check'));
1.297     www      2058:     }
1.300     albertel 2059:     if ($perm{'opa'}) {
1.297     www      2060: 	$request->print('<br />'.
1.300     albertel 2061: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2062: 					 $uname,$udom,$symb,'check'));
1.297     www      2063:     }
1.41      ng       2064: 
                   2065:     my %seen = ();
                   2066:     my @partlist;
1.129     ng       2067:     my @gradePartRespid;
1.375     albertel 2068:     my @part_response_id = &flatten_responseType($responseType);
                   2069:     foreach my $part_response_id (@part_response_id) {
                   2070:     	my ($partid,$respid) = @{ $part_response_id };
                   2071: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2072: 	next if ($seen{$partid} > 0);
1.41      ng       2073: 	$seen{$partid}++;
1.393     albertel 2074: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2075: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2076: 	push @partlist,$partid;
1.129     ng       2077: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2078: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2079:     }
1.45      ng       2080:     $result='<input type="hidden" name="partlist'.$counter.
                   2081: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2082:     $result.='<input type="hidden" name="gradePartRespid'.
                   2083: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2084:     my $ctr = 0;
                   2085:     while ($ctr < scalar(@partlist)) {
                   2086: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2087: 	    $partlist[$ctr].'" />'."\n";
                   2088: 	$ctr++;
                   2089:     }
                   2090:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       2091: 
                   2092:     # print end of form
                   2093:     if ($counter == $total) {
1.297     www      2094: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2095: 	$endform.='<input type="button" value="Save & Next" '.
                   2096: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2097: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2098: 	my $ntstu ='<select name="NTSTU">'.
                   2099: 	    '<option>1</option><option>2</option>'.
                   2100: 	    '<option>3</option><option>5</option>'.
                   2101: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2102: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2103: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.119     ng       2104: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2105: 	$endform.='<input type="button" value="Previous" '.
1.417     albertel 2106: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.126     ng       2107: 	    '<input type="button" value="Next" '.
1.417     albertel 2108: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.126     ng       2109: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2110:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2111:             "' name='increment' />";
1.45      ng       2112: 	$endform.='</td><tr></table></form>';
1.324     albertel 2113: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2114: 	$request->print($endform);
                   2115:     }
                   2116:     return '';
1.38      ng       2117: }
                   2118: 
1.44      ng       2119: #--- Retrieve the last submission for all the parts
1.38      ng       2120: sub get_last_submission {
1.119     ng       2121:     my ($returnhash)=@_;
1.46      ng       2122:     my (@string,$timestamp);
1.119     ng       2123:     if ($$returnhash{'version'}) {
1.46      ng       2124: 	my %lasthash=();
                   2125: 	my ($version);
1.119     ng       2126: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2127: 	    foreach my $key (sort(split(/\:/,
                   2128: 					$$returnhash{$version.':keys'}))) {
                   2129: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2130: 		$timestamp = 
                   2131: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2132: 	    }
                   2133: 	}
1.397     albertel 2134: 	foreach my $key (keys(%lasthash)) {
                   2135: 	    next if ($key !~ /\.submission$/);
                   2136: 
                   2137: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2138: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2139: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2140: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2141: 	}
                   2142:     }
1.397     albertel 2143:     if (!@string) {
                   2144: 	$string[0] =
1.398     albertel 2145: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2146:     }
                   2147:     return (\@string,\$timestamp);
1.38      ng       2148: }
1.35      ng       2149: 
1.44      ng       2150: #--- High light keywords, with style choosen by user.
1.38      ng       2151: sub keywords_highlight {
1.44      ng       2152:     my $string    = shift;
1.257     albertel 2153:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2154:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2155:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2156:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2157:     foreach my $keyword (@keylist) {
                   2158: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2159:     }
                   2160:     return $string;
1.38      ng       2161: }
1.36      ng       2162: 
1.44      ng       2163: #--- Called from submission routine
1.38      ng       2164: sub processHandGrade {
1.41      ng       2165:     my ($request) = shift;
1.324     albertel 2166:     my $symb   = &get_symb($request);
                   2167:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2168:     my $button = $env{'form.gradeOpt'};
                   2169:     my $ngrade = $env{'form.NCT'};
                   2170:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2171:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2172:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2173: 
1.44      ng       2174:     if ($button eq 'Save & Next') {
                   2175: 	my $ctr = 0;
                   2176: 	while ($ctr < $ngrade) {
1.257     albertel 2177: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2178: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2179: 	    if ($errorflag eq 'no_score') {
                   2180: 		$ctr++;
                   2181: 		next;
                   2182: 	    }
1.104     albertel 2183: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2184: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2185: 		$ctr++;
                   2186: 		next;
                   2187: 	    }
1.257     albertel 2188: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2189: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2190: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2191:             my ($feedurl,$showsymb) =
                   2192: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2193: 	    my $messagetail;
1.62      albertel 2194: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2195: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2196: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2197: 		$subject.=' ['.$restitle.']';
1.44      ng       2198: 		my (@msgnum) = split(/,/,$includemsg);
                   2199: 		foreach (@msgnum) {
1.257     albertel 2200: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2201: 		}
1.80      ng       2202: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2203: 		if ($env{'form.withgrades'.$ctr}) {
                   2204: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2205: 		    $messagetail = " for <a href=\"".
1.418     albertel 2206: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2207: 		}
                   2208: 		$msgstatus = 
                   2209:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2210: 						     $message.$messagetail,
1.418     albertel 2211:                                                      undef,$feedurl,undef,
1.386     raeburn  2212:                                                      undef,undef,$showsymb,
                   2213:                                                      $restitle);
                   2214: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2215: 				$msgstatus);
1.44      ng       2216: 	    }
1.257     albertel 2217: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2218: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2219: 		foreach my $collabstr (@collabstrs) {
                   2220: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2221: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2222: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2223: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2224: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2225: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2226: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2227: 			    next;
1.418     albertel 2228: 			} elsif ($message ne '') {
                   2229: 			    my ($baseurl,$showsymb) = 
                   2230: 				&get_feedurl_and_symb($symb,$collaborator,
                   2231: 						      $udom);
                   2232: 			    if ($env{'form.withgrades'.$ctr}) {
                   2233: 				$messagetail = " for <a href=\"".
1.386     raeburn  2234:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2235: 			    }
1.418     albertel 2236: 			    $msgstatus = 
                   2237: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2238: 			}
1.44      ng       2239: 		    }
                   2240: 		}
                   2241: 	    }
                   2242: 	    $ctr++;
                   2243: 	}
                   2244:     }
                   2245: 
1.257     albertel 2246:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2247: 	# Keywords sorted in alphabatical order
1.257     albertel 2248: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2249: 	my %keyhash = ();
1.257     albertel 2250: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2251: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2252: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2253: 	$env{'form.keywords'} = join(' ',@keywords);
                   2254: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2255: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2256: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2257: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2258: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2259: 
                   2260: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2261: 	# New messages are saved in env for the next student.
1.119     ng       2262: 	# All messages are saved in nohist_handgrade.db
                   2263: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2264: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2265: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2266: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2267: 		$idx++;
                   2268: 	    }
                   2269: 	    $ctr++;
1.41      ng       2270: 	}
1.119     ng       2271: 	$ctr = 0;
                   2272: 	while ($ctr < $ngrade) {
1.257     albertel 2273: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2274: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2275: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2276: 		$idx++;
                   2277: 	    }
                   2278: 	    $ctr++;
1.41      ng       2279: 	}
1.257     albertel 2280: 	$env{'form.savemsgN'} = --$idx;
                   2281: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2282: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2283: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2284:     }
1.44      ng       2285:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2286:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2287:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2288: 	my ($ctr,$total) = (0,0);
                   2289: 	while ($ctr < $ngrade) {
1.257     albertel 2290: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2291: 	    $ctr++;
                   2292: 	}
1.257     albertel 2293: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2294: 	$ctr = 0;
                   2295: 	while ($ctr < $total) {
1.257     albertel 2296: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2297: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2298: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2299: 	    &submission($request,$ctr,$total-1);
1.41      ng       2300: 	    $ctr++;
                   2301: 	}
                   2302: 	return '';
                   2303:     }
1.36      ng       2304: 
1.121     ng       2305: # Go directly to grade student - from submission or link from chart page
1.120     ng       2306:     if ($button eq 'Grade Student') {
1.324     albertel 2307: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2308: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2309: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2310: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2311: 	&submission($request,0,0);
                   2312: 	return '';
                   2313:     }
                   2314: 
1.44      ng       2315:     # Get the next/previous one or group of students
1.257     albertel 2316:     my $firststu = $env{'form.unamedom0'};
                   2317:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2318:     my $ctr = 2;
1.41      ng       2319:     while ($laststu eq '') {
1.257     albertel 2320: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2321: 	$ctr++;
                   2322: 	$laststu = $firststu if ($ctr > $ngrade);
                   2323:     }
1.44      ng       2324: 
1.41      ng       2325:     my (@parsedlist,@nextlist);
                   2326:     my ($nextflg) = 0;
1.294     albertel 2327:     foreach (sort 
                   2328: 	     {
                   2329: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2330: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2331: 		 }
                   2332: 		 return $a cmp $b;
                   2333: 	     } (keys(%$fullname))) {
1.41      ng       2334: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2335: 	    push @parsedlist,$_;
                   2336: 	}
                   2337: 	$nextflg = 1 if ($_ eq $laststu);
                   2338: 	if ($button eq 'Previous') {
                   2339: 	    last if ($_ eq $firststu);
                   2340: 	    push @parsedlist,$_;
                   2341: 	}
                   2342:     }
                   2343:     $ctr = 0;
                   2344:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2345:     my ($partlist) = &response_type($symb);
1.41      ng       2346:     foreach my $student (@parsedlist) {
1.257     albertel 2347: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2348: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2349: 	
                   2350: 	if ($submitonly eq 'queued') {
                   2351: 	    my %queue_status = 
                   2352: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2353: 							$udom,$uname);
                   2354: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2355: 	}
                   2356: 
1.156     albertel 2357: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2358: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2359: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2360: 	    my $submitted = 0;
1.248     albertel 2361: 	    my $ungraded = 0;
                   2362: 	    my $incorrect = 0;
1.145     albertel 2363: 	    foreach (keys(%status)) {
                   2364: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2365: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2366: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2367: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2368: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2369: 		    $submitted = 0;
                   2370: 		}
1.41      ng       2371: 	    }
1.156     albertel 2372: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2373: 				     $submitonly eq 'incorrect' ||
                   2374: 				     $submitonly eq 'graded'));
1.248     albertel 2375: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2376: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2377: 	}
                   2378: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2379: 	last if ($ctr == $ntstu);
1.41      ng       2380: 	$ctr++;
                   2381:     }
1.36      ng       2382: 
1.41      ng       2383:     $ctr = 0;
                   2384:     my $total = scalar(@nextlist)-1;
1.39      ng       2385: 
1.41      ng       2386:     foreach (sort @nextlist) {
                   2387: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2388: 	$env{'form.student'}  = $uname;
                   2389: 	$env{'form.userdom'}  = $udom;
                   2390: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2391: 	&submission($request,$ctr,$total);
                   2392: 	$ctr++;
                   2393:     }
                   2394:     if ($total < 0) {
1.398     albertel 2395: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
1.41      ng       2396: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2397: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2398: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2399: 	$request->print($the_end);
                   2400:     }
                   2401:     return '';
1.38      ng       2402: }
1.36      ng       2403: 
1.44      ng       2404: #---- Save the score and award for each student, if changed
1.38      ng       2405: sub saveHandGrade {
1.324     albertel 2406:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2407:     my @version_parts;
1.104     albertel 2408:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2409: 					   $env{'request.course.id'});
1.104     albertel 2410:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2411:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2412:     my @parts_graded;
1.77      ng       2413:     my %newrecord  = ();
                   2414:     my ($pts,$wgt) = ('','');
1.269     raeburn  2415:     my %aggregate = ();
                   2416:     my $aggregateflag = 0;
1.301     albertel 2417:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2418:     foreach my $new_part (@parts) {
1.337     banghart 2419: 	#collaborator ($submi may vary for different parts
1.259     banghart 2420: 	if ($submitter && $new_part ne $part) { next; }
                   2421: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2422: 	if ($dropMenu eq 'excused') {
1.259     banghart 2423: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2424: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2425: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2426: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2427: 		}
1.364     banghart 2428: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2429: 	    }
1.125     ng       2430: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2431: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2432: 	    foreach my $key (keys (%record)) {
1.259     banghart 2433: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2434: 	    }
1.259     banghart 2435: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2436: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2437:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2438: 
                   2439:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2440: 					       [$new_part]);
                   2441:             my $aggtries =$totaltries;
1.269     raeburn  2442:             if ($last_resets{$new_part}) {
1.270     albertel 2443:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2444: 					   $new_part);
1.269     raeburn  2445:             }
1.270     albertel 2446: 
                   2447:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2448:             if ($aggtries > 0) {
1.327     albertel 2449:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2450:                 $aggregateflag = 1;
                   2451:             }
1.125     ng       2452: 	} elsif ($dropMenu eq '') {
1.259     banghart 2453: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2454: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2455: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2456: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2457: 		next;
                   2458: 	    }
1.259     banghart 2459: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2460: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2461: 	    my $partial= $pts/$wgt;
1.259     banghart 2462: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2463: 		#do not update score for part if not changed.
1.346     banghart 2464:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2465: 		next;
1.251     banghart 2466: 	    } else {
1.259     banghart 2467: 	        push @parts_graded, $new_part;
1.153     albertel 2468: 	    }
1.259     banghart 2469: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2470: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2471: 	    }
1.259     banghart 2472: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2473: 	    if ($partial == 0) {
1.153     albertel 2474: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2475: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2476: 		}
1.41      ng       2477: 	    } else {
1.153     albertel 2478: 		if ($record{$reckey} ne 'correct_by_override') {
                   2479: 		    $newrecord{$reckey} = 'correct_by_override';
                   2480: 		}
                   2481: 	    }	    
                   2482: 	    if ($submitter && 
1.259     banghart 2483: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2484: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2485: 	    }
1.259     banghart 2486: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2487: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2488: 	}
1.259     banghart 2489: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2490: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2491: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2492: 	        $dropMenu eq 'reset status')
                   2493: 	   {
1.342     banghart 2494: 	    push (@version_parts,$new_part);
1.259     banghart 2495: 	}
1.41      ng       2496:     }
1.301     albertel 2497:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2498:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2499: 
1.344     albertel 2500:     if (%newrecord) {
                   2501:         if (@version_parts) {
1.364     banghart 2502:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2503:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2504: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2505: 	    foreach my $new_part (@version_parts) {
                   2506: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2507: 				$new_part,\%newrecord);
                   2508: 	    }
1.259     banghart 2509:         }
1.44      ng       2510: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2511: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2512: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2513: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2514:     }
1.269     raeburn  2515:     if ($aggregateflag) {
                   2516:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2517: 			      $cdom,$cnum);
1.269     raeburn  2518:     }
1.301     albertel 2519:     return ('',$pts,$wgt);
1.36      ng       2520: }
1.322     albertel 2521: 
1.380     albertel 2522: sub check_and_remove_from_queue {
                   2523:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2524:     my @ungraded_parts;
                   2525:     foreach my $part (@{$parts}) {
                   2526: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2527: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2528: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2529: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2530: 		) {
                   2531: 	    push(@ungraded_parts, $part);
                   2532: 	}
                   2533:     }
                   2534:     if ( !@ungraded_parts ) {
                   2535: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2536: 					       $cnum,$domain,$stuname);
                   2537:     }
                   2538: }
                   2539: 
1.337     banghart 2540: sub handback_files {
                   2541:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2542:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2543:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2544: 
                   2545:     my @part_response_id = &flatten_responseType($responseType);
                   2546:     foreach my $part_response_id (@part_response_id) {
                   2547:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2548: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2549:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2550:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2551:                 my $file_counter = 1;
1.367     albertel 2552: 		my $file_msg;
1.337     banghart 2553:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2554:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2555:                     my ($directory,$answer_file) = 
                   2556:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2557:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2558: 		        &file_name_version_ext($answer_file);
1.355     banghart 2559: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2560: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2561: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2562:                     # fix file name
                   2563:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2564:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2565:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2566:             	                                $save_file_name);
1.337     banghart 2567:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2568:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2569:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2570:                     } else {
1.360     banghart 2571:                         # mark the file as read only
                   2572:                         my @files = ($save_file_name);
1.372     albertel 2573:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2574:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2575: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2576: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2577: 			}
                   2578:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2579: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2580: 
1.337     banghart 2581:                     }
                   2582:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2583:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2584:                     $file_counter++;
                   2585:                 }
1.367     albertel 2586: 		my $subject = "File Handed Back by Instructor ";
                   2587: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2588: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2589: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2590: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2591: 		my ($feedurl,$showsymb) = 
                   2592: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2593:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2594: 		my $msgstatus = 
                   2595:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2596: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2597:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2598:             }
                   2599:         }
1.338     banghart 2600:     return;
1.337     banghart 2601: }
                   2602: 
1.418     albertel 2603: sub get_feedurl_and_symb {
                   2604:     my ($symb,$uname,$udom) = @_;
                   2605:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2606:     $url = &Apache::lonnet::clutter($url);
                   2607:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2608: 					$symb,$udom,$uname);
                   2609:     if ($encrypturl =~ /^yes$/i) {
                   2610: 	&Apache::lonenc::encrypted(\$url,1);
                   2611: 	&Apache::lonenc::encrypted(\$symb,1);
                   2612:     }
                   2613:     return ($url,$symb);
                   2614: }
                   2615: 
1.313     banghart 2616: sub get_submitted_files {
                   2617:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2618:     my @files;
                   2619:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2620:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2621:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2622:     	    push(@files,$file_url.$file);
                   2623:         }
                   2624:     }
                   2625:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2626:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2627:     }
                   2628:     return (\@files);
                   2629: }
1.322     albertel 2630: 
1.269     raeburn  2631: # ----------- Provides number of tries since last reset.
                   2632: sub get_num_tries {
                   2633:     my ($record,$last_reset,$part) = @_;
                   2634:     my $timestamp = '';
                   2635:     my $num_tries = 0;
                   2636:     if ($$record{'version'}) {
                   2637:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2638:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2639:                 $timestamp = $$record{$version.':timestamp'};
                   2640:                 if ($timestamp > $last_reset) {
                   2641:                     $num_tries ++;
                   2642:                 } else {
                   2643:                     last;
                   2644:                 }
                   2645:             }
                   2646:         }
                   2647:     }
                   2648:     return $num_tries;
                   2649: }
                   2650: 
                   2651: # ----------- Determine decrements required in aggregate totals 
                   2652: sub decrement_aggs {
                   2653:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2654:     my %decrement = (
                   2655:                         attempts => 0,
                   2656:                         users => 0,
                   2657:                         correct => 0
                   2658:                     );
                   2659:     $decrement{'attempts'} = $aggtries;
                   2660:     if ($solvedstatus =~ /^correct/) {
                   2661:         $decrement{'correct'} = 1;
                   2662:     }
                   2663:     if ($aggtries == $totaltries) {
                   2664:         $decrement{'users'} = 1;
                   2665:     }
                   2666:     foreach my $type (keys (%decrement)) {
                   2667:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2668:     }
                   2669:     return;
                   2670: }
                   2671: 
                   2672: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2673: sub get_last_resets {
1.270     albertel 2674:     my ($symb,$courseid,$partids) =@_;
                   2675:     my %last_resets;
1.269     raeburn  2676:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2677:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2678:     my @keys;
                   2679:     foreach my $part (@{$partids}) {
                   2680: 	push(@keys,"$symb\0$part\0resettime");
                   2681:     }
                   2682:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2683: 				     $cdom,$cname);
                   2684:     foreach my $part (@{$partids}) {
                   2685: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2686:     }
1.270     albertel 2687:     return %last_resets;
1.269     raeburn  2688: }
                   2689: 
1.251     banghart 2690: # ----------- Handles creating versions for portfolio files as answers
                   2691: sub version_portfiles {
1.343     banghart 2692:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2693:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2694:     my @returned_keys;
1.255     banghart 2695:     my $parts = join('|', @$parts_graded);
1.359     www      2696:     my $portfolio_root = &propath($domain,$stu_name).
                   2697: 	'/userfiles/portfolio';
1.277     albertel 2698:     foreach my $key (keys(%$record)) {
1.259     banghart 2699:         my $new_portfiles;
1.263     banghart 2700:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2701:             my @versioned_portfiles;
1.367     albertel 2702:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2703:             foreach my $file (@portfiles) {
1.306     banghart 2704:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2705:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2706: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2707: 		    &file_name_version_ext($answer_file);
1.306     banghart 2708:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2709:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2710:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2711:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2712:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2713:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2714:                         [$directory.$new_answer],
1.306     banghart 2715:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2716:                 }
1.252     banghart 2717:             }
1.343     banghart 2718:             $$record{$key} = join(',',@versioned_portfiles);
                   2719:             push(@returned_keys,$key);
1.251     banghart 2720:         }
                   2721:     } 
1.343     banghart 2722:     return (@returned_keys);   
1.305     banghart 2723: }
                   2724: 
1.307     banghart 2725: sub get_next_version {
1.341     banghart 2726:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2727:     my $version;
                   2728:     foreach my $row (@$dir_list) {
                   2729:         my ($file) = split(/\&/,$row,2);
                   2730:         my ($file_name,$file_version,$file_ext) =
                   2731: 	    &file_name_version_ext($file);
                   2732:         if (($file_name eq $answer_name) && 
                   2733: 	    ($file_ext eq $answer_ext)) {
                   2734:                 # gets here if filename and extension match, regardless of version
                   2735:                 if ($file_version ne '') {
                   2736:                 # a versioned file is found  so save it for later
                   2737:                 if ($file_version > $version) {
                   2738: 		    $version = $file_version;
                   2739: 	        }
                   2740:             }
                   2741:         }
                   2742:     } 
                   2743:     $version ++;
                   2744:     return($version);
                   2745: }
                   2746: 
1.305     banghart 2747: sub version_selected_portfile {
1.306     banghart 2748:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2749:     my ($answer_name,$answer_ver,$answer_ext) =
                   2750:         &file_name_version_ext($file_name);
                   2751:     my $new_answer;
                   2752:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2753:     if($env{'form.copy'} eq '-1') {
                   2754:         &Apache::lonnet::logthis('problem getting file '.$file_name);
                   2755:         $new_answer = 'problem getting file';
                   2756:     } else {
                   2757:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2758:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2759:                             $stu_name,$domain,'copy',
                   2760: 		        '/portfolio'.$directory.$new_answer);
                   2761:     }    
                   2762:     return ($new_answer);
1.251     banghart 2763: }
                   2764: 
1.304     albertel 2765: sub file_name_version_ext {
                   2766:     my ($file)=@_;
                   2767:     my @file_parts = split(/\./, $file);
                   2768:     my ($name,$version,$ext);
                   2769:     if (@file_parts > 1) {
                   2770: 	$ext=pop(@file_parts);
                   2771: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2772: 	    $version=pop(@file_parts);
                   2773: 	}
                   2774: 	$name=join('.',@file_parts);
                   2775:     } else {
                   2776: 	$name=join('.',@file_parts);
                   2777:     }
                   2778:     return($name,$version,$ext);
                   2779: }
                   2780: 
1.44      ng       2781: #--------------------------------------------------------------------------------------
                   2782: #
                   2783: #-------------------------- Next few routines handles grading by section or whole class
                   2784: #
                   2785: #--- Javascript to handle grading by section or whole class
1.42      ng       2786: sub viewgrades_js {
                   2787:     my ($request) = shift;
                   2788: 
1.41      ng       2789:     $request->print(<<VIEWJAVASCRIPT);
                   2790: <script type="text/javascript" language="javascript">
1.45      ng       2791:    function writePoint(partid,weight,point) {
1.125     ng       2792: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2793: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2794: 	if (point == "textval") {
1.125     ng       2795: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2796: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2797: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2798: 		var resetbox = false;
                   2799: 		for (var i=0; i<radioButton.length; i++) {
                   2800: 		    if (radioButton[i].checked) {
                   2801: 			textbox.value = i;
                   2802: 			resetbox = true;
                   2803: 		    }
                   2804: 		}
                   2805: 		if (!resetbox) {
                   2806: 		    textbox.value = "";
                   2807: 		}
                   2808: 		return;
                   2809: 	    }
1.109     matthew  2810: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2811: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2812: 				   ") greater than the weight for the part. Accept?");
                   2813: 		if (resp == false) {
                   2814: 		    textbox.value = "";
                   2815: 		    return;
                   2816: 		}
                   2817: 	    }
1.42      ng       2818: 	    for (var i=0; i<radioButton.length; i++) {
                   2819: 		radioButton[i].checked=false;
1.109     matthew  2820: 		if (parseFloat(point) == i) {
1.42      ng       2821: 		    radioButton[i].checked=true;
                   2822: 		}
                   2823: 	    }
1.41      ng       2824: 
1.42      ng       2825: 	} else {
1.125     ng       2826: 	    textbox.value = parseFloat(point);
1.42      ng       2827: 	}
1.41      ng       2828: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2829: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2830: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2831: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2832: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2833: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2834: 	    if (saveval != "correct") {
                   2835: 		scorename.value = point;
1.43      ng       2836: 		if (selname[0].selected != true) {
                   2837: 		    selname[0].selected = true;
                   2838: 		}
1.42      ng       2839: 	    }
                   2840: 	}
1.125     ng       2841: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2842:     }
                   2843: 
                   2844:     function writeRadText(partid,weight) {
1.125     ng       2845: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2846: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2847:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2848: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2849: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2850: 	    for (var i=0; i<radioButton.length; i++) {
                   2851: 		radioButton[i].checked=false;
                   2852: 
                   2853: 	    }
                   2854: 	    textbox.value = "";
                   2855: 
                   2856: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2857: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2858: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2859: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2860: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2861: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2862: 		if ((saveval != "correct") || override) {
1.42      ng       2863: 		    scorename.value = "";
1.125     ng       2864: 		    if (selval[1].selected) {
                   2865: 			selname[1].selected = true;
                   2866: 		    } else {
                   2867: 			selname[2].selected = true;
                   2868: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   2869: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   2870: 		    }
1.42      ng       2871: 		}
                   2872: 	    }
1.43      ng       2873: 	} else {
                   2874: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2875: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2876: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2877: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2878: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2879: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2880: 		if ((saveval != "correct") || override) {
1.125     ng       2881: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       2882: 		    selname[0].selected = true;
                   2883: 		}
                   2884: 	    }
                   2885: 	}	    
1.42      ng       2886:     }
                   2887: 
                   2888:     function changeSelect(partid,user) {
1.125     ng       2889: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2890: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       2891: 	var point  = textbox.value;
1.125     ng       2892: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       2893: 
1.109     matthew  2894: 	if (isNaN(point) || parseFloat(point) < 0) {
                   2895: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       2896: 	    textbox.value = "";
                   2897: 	    return;
                   2898: 	}
1.109     matthew  2899: 	if (parseFloat(point) > parseFloat(weight)) {
                   2900: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2901: 			       ") greater than the weight of the part. Accept?");
                   2902: 	    if (resp == false) {
                   2903: 		textbox.value = "";
                   2904: 		return;
                   2905: 	    }
                   2906: 	}
1.42      ng       2907: 	selval[0].selected = true;
                   2908:     }
                   2909: 
                   2910:     function changeOneScore(partid,user) {
1.125     ng       2911: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2912: 	if (selval[1].selected || selval[2].selected) {
                   2913: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   2914: 	    if (selval[2].selected) {
                   2915: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   2916: 	    }
1.269     raeburn  2917:         }
1.42      ng       2918:     }
                   2919: 
                   2920:     function resetEntry(numpart) {
                   2921: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       2922: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   2923: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   2924: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   2925: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       2926: 	    for (var i=0; i<radioButton.length; i++) {
                   2927: 		radioButton[i].checked=false;
                   2928: 
                   2929: 	    }
                   2930: 	    textbox.value = "";
                   2931: 	    selval[0].selected = true;
                   2932: 
                   2933: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2934: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2935: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2936: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2937: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   2938: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   2939: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   2940: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2941: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2942: 		if (saveselval == "excused") {
1.43      ng       2943: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       2944: 		} else {
1.43      ng       2945: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       2946: 		}
                   2947: 	    }
1.41      ng       2948: 	}
1.42      ng       2949:     }
                   2950: 
1.41      ng       2951: </script>
                   2952: VIEWJAVASCRIPT
1.42      ng       2953: }
                   2954: 
1.44      ng       2955: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       2956: sub viewgrades {
                   2957:     my ($request) = shift;
                   2958:     &viewgrades_js($request);
1.41      ng       2959: 
1.324     albertel 2960:     my ($symb) = &get_symb($request);
1.168     albertel 2961:     #need to make sure we have the correct data for later EXT calls, 
                   2962:     #thus invalidate the cache
                   2963:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 2964:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   2965:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 2966:     &Apache::lonnet::clear_EXT_cache_status();
                   2967: 
1.398     albertel 2968:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   2969:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       2970: 
                   2971:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 2972:     $result.=&jscriptNform($symb);
1.41      ng       2973: 
1.44      ng       2974:     #beginning of class grading form
1.41      ng       2975:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 2976: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       2977: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432   ! banghart 2978: 	&build_section_inputs().
1.257     albertel 2979: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   2980: 	'<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
                   2981: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       2982: 
1.126     ng       2983:     my $sectionClass;
1.430     banghart 2984:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 2985:     if ($env{'form.section'} eq 'all') {
1.126     ng       2986: 	$sectionClass='Class </h3>';
1.257     albertel 2987:     } elsif ($env{'form.section'} eq 'none') {
1.431     banghart 2988: 	$sectionClass=&mt('Students in no Section').'</h3>';
1.52      albertel 2989:     } else {
1.431     banghart 2990: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
1.52      albertel 2991:     }
1.431     banghart 2992:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
1.52      albertel 2993:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   2994: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       2995:     #radio buttons/text box for assigning points for a section or class.
                   2996:     #handles different parts of a problem
1.375     albertel 2997:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       2998:     my %weight = ();
                   2999:     my $ctsparts = 0;
1.41      ng       3000:     $result.='<table border="0">';
1.45      ng       3001:     my %seen = ();
1.375     albertel 3002:     my @part_response_id = &flatten_responseType($responseType);
                   3003:     foreach my $part_response_id (@part_response_id) {
                   3004:     	my ($partid,$respid) = @{ $part_response_id };
                   3005: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3006: 	next if $seen{$partid};
                   3007: 	$seen{$partid}++;
1.375     albertel 3008: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3009: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3010: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3011: 
1.44      ng       3012: 	$result.='<input type="hidden" name="partid_'.
                   3013: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3014: 	$result.='<input type="hidden" name="weight_'.
                   3015: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3016: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 3017: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3018: 	$result.='<table border="0"><tr>';  
1.41      ng       3019: 	my $ctr = 0;
1.42      ng       3020: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3021: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3022: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3023: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3024: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3025: 	    $ctr++;
                   3026: 	}
                   3027: 	$result.='</tr></table>';
1.44      ng       3028: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3029: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3030: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3031: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   3032: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3033: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3034: 		$weight{$partid}.')"> '.
1.401     albertel 3035: 	    '<option selected="selected"> </option>'.
1.125     ng       3036: 	    '<option>excused</option>'.
1.265     www      3037: 	    '<option>reset status</option></select></td>'.
1.266     albertel 3038:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       3039: 	$ctsparts++;
1.41      ng       3040:     }
1.52      albertel 3041:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   3042: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3043:     $result.='<input type="button" value="Revert to Default" '.
1.417     albertel 3044: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
1.41      ng       3045: 
1.44      ng       3046:     #table listing all the students in a section/class
                   3047:     #header of table
1.126     ng       3048:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       3049:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       3050: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       3051: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 3052:     my (@parts) = sort(&getpartlist($symb));
                   3053:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3054:     my @partids = ();
1.41      ng       3055:     foreach my $part (@parts) {
                   3056: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3057: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3058: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3059: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3060:         push(@partids, $partid);
1.324     albertel 3061: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3062: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 3063: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   3064: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       3065: 	    next;
1.207     albertel 3066: 	} else {
                   3067: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3068: 	}
1.53      albertel 3069: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 3070: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       3071:     }
                   3072:     $result.='</tr>';
1.44      ng       3073: 
1.270     albertel 3074:     my %last_resets = 
                   3075: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3076: 
1.41      ng       3077:     #get info for each student
1.44      ng       3078:     #list all the students - with points and grade status
1.257     albertel 3079:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3080:     my $ctr = 0;
1.294     albertel 3081:     foreach (sort 
                   3082: 	     {
                   3083: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3084: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3085: 		 }
                   3086: 		 return $a cmp $b;
                   3087: 	     } (keys(%$fullname))) {
1.126     ng       3088: 	$ctr++;
1.324     albertel 3089: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3090: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3091:     }
                   3092:     $result.='</table></td></tr></table>';
                   3093:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3094:     $result.='<input type="button" value="Save" '.
1.417     albertel 3095: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3096:     if (scalar(%$fullname) eq 0) {
                   3097: 	my $colspan=3+scalar(@parts);
1.398     albertel 3098: 	$result='<span class="LC_warning">There are no students in section "'.$env{'form.section'}.
                   3099: 	    '" with enrollment status "'.$env{'form.Status'}.'" to modify or grade.</span>';
1.96      albertel 3100:     }
1.324     albertel 3101:     $result.=&show_grading_menu_form($symb);
1.41      ng       3102:     return $result;
                   3103: }
                   3104: 
1.44      ng       3105: #--- call by previous routine to display each student
1.41      ng       3106: sub viewstudentgrade {
1.324     albertel 3107:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3108:     my ($uname,$udom) = split(/:/,$student);
                   3109:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3110:     my %aggregates = (); 
1.233     albertel 3111:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3112: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3113: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3114: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3115: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3116: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3117:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3118:     foreach my $apart (@$parts) {
                   3119: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3120: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3121:         $result.='<td align="center">';
1.269     raeburn  3122:         my ($aggtries,$totaltries);
                   3123:         unless (exists($aggregates{$part})) {
1.270     albertel 3124: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3125: 
                   3126: 	    $aggtries = $totaltries;
1.269     raeburn  3127:             if ($$last_resets{$part}) {  
1.270     albertel 3128:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3129: 					   $part);
                   3130:             }
1.269     raeburn  3131:             $result.='<input type="hidden" name="'.
                   3132:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3133:             $result.='<input type="hidden" name="'.
                   3134:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3135:             $aggregates{$part} = 1;
                   3136:         }
1.41      ng       3137: 	if ($type eq 'awarded') {
1.320     albertel 3138: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3139: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3140: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3141: 	    $result.='<input type="text" name="'.
1.89      albertel 3142: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3143: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3144: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3145: 	} elsif ($type eq 'solved') {
                   3146: 	    my ($status,$foo)=split(/_/,$score,2);
                   3147: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3148: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3149: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3150: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3151: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3152: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3153: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3154: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3155: 	    $result.='<option>reset status</option>';
1.126     ng       3156: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3157: 	} else {
                   3158: 	    $result.='<input type="hidden" name="'.
                   3159: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3160: 		    "\n";
1.233     albertel 3161: 	    $result.='<input type="text" name="'.
1.122     ng       3162: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3163: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3164: 	}
                   3165:     }
                   3166:     $result.='</tr>';
                   3167:     return $result;
1.38      ng       3168: }
                   3169: 
1.44      ng       3170: #--- change scores for all the students in a section/class
                   3171: #    record does not get update if unchanged
1.38      ng       3172: sub editgrades {
1.41      ng       3173:     my ($request) = @_;
                   3174: 
1.324     albertel 3175:     my $symb=&get_symb($request);
1.398     albertel 3176:     my $title='<h3><span class="LC_info">Current Grade Status</span></h3>';
                   3177:     $title.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4><br />'."\n";
                   3178:     $title.='<h4><b>Section: </b>'.$env{'form.section'}.'</h4>'."\n";
1.126     ng       3179: 
1.44      ng       3180:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3181:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3182: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3183: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3184: 
                   3185:     my %scoreptr = (
                   3186: 		    'correct'  =>'correct_by_override',
                   3187: 		    'incorrect'=>'incorrect_by_override',
                   3188: 		    'excused'  =>'excused',
                   3189: 		    'ungraded' =>'ungraded_attempted',
                   3190: 		    'nothing'  => '',
                   3191: 		    );
1.257     albertel 3192:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3193: 
1.44      ng       3194:     my (@partid);
                   3195:     my %weight = ();
1.54      albertel 3196:     my %columns = ();
1.44      ng       3197:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3198: 
1.324     albertel 3199:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3200:     my $header;
1.257     albertel 3201:     while ($ctr < $env{'form.totalparts'}) {
                   3202: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3203: 	push @partid,$partid;
1.257     albertel 3204: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3205: 	$ctr++;
1.54      albertel 3206:     }
1.324     albertel 3207:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3208:     foreach my $partid (@partid) {
                   3209: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3210: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3211: 	$columns{$partid}=2;
                   3212: 	foreach my $stores (@parts) {
                   3213: 	    my ($part,$type) = &split_part_type($stores);
                   3214: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3215: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3216: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3217: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3218: 	    $display =~ s/Number of Attempts/Tries/;
                   3219: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3220: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3221: 	    $columns{$partid}+=2;
                   3222: 	}
                   3223:     }
                   3224:     foreach my $partid (@partid) {
1.324     albertel 3225: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3226: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3227: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3228: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3229: 
1.44      ng       3230:     }
                   3231:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3232:     $result .= $header;
1.44      ng       3233:     $result .= '</tr>'."\n";
1.93      albertel 3234:     my $noupdate;
1.126     ng       3235:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3236:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3237: 	my $line;
1.257     albertel 3238: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3239: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3240: 	my %newrecord;
                   3241: 	my $updateflag = 0;
1.281     albertel 3242: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3243: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3244: 	if (!&canmodify($usec)) {
1.126     ng       3245: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3246: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3247: 	    next;
                   3248: 	}
1.269     raeburn  3249:         my %aggregate = ();
                   3250:         my $aggregateflag = 0;
1.281     albertel 3251: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3252: 	foreach (@partid) {
1.257     albertel 3253: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3254: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3255: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3256: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3257: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3258: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3259: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3260: 	    my $score;
                   3261: 	    if ($partial eq '') {
1.257     albertel 3262: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3263: 	    } elsif ($partial > 0) {
                   3264: 		$score = 'correct_by_override';
                   3265: 	    } elsif ($partial == 0) {
                   3266: 		$score = 'incorrect_by_override';
                   3267: 	    }
1.257     albertel 3268: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3269: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3270: 
1.292     albertel 3271: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3272: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3273: 	    if ($dropMenu eq 'reset status' &&
                   3274: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3275: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3276: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3277: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3278: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3279: 		$updateflag = 1;
1.269     raeburn  3280:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3281:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3282:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3283:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3284:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3285:                     $aggregateflag = 1;
                   3286:                 }
1.139     albertel 3287: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3288: 		$updateflag = 1;
                   3289: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3290: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3291: 		$rec_update++;
1.125     ng       3292: 	    }
                   3293: 
1.93      albertel 3294: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3295: 		'<td align="center">'.$awarded.
                   3296: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3297: 
1.54      albertel 3298: 
                   3299: 	    my $partid=$_;
                   3300: 	    foreach my $stores (@parts) {
                   3301: 		my ($part,$type) = &split_part_type($stores);
                   3302: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3303: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3304: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3305: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3306: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3307: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3308: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3309: 		    $updateflag=1;
                   3310: 		}
1.93      albertel 3311: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3312: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3313: 	    }
1.44      ng       3314: 	}
1.93      albertel 3315: 	$line.='</tr>'."\n";
1.301     albertel 3316: 
                   3317: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3318: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3319: 
1.44      ng       3320: 	if ($updateflag) {
                   3321: 	    $count++;
1.257     albertel 3322: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3323: 				    $udom,$uname);
1.301     albertel 3324: 
                   3325: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3326: 					      $cnum,$udom,$uname)) {
                   3327: 		# need to figure out if should be in queue.
                   3328: 		my %record =  
                   3329: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3330: 					     $udom,$uname);
                   3331: 		my $all_graded = 1;
                   3332: 		my $none_graded = 1;
                   3333: 		foreach my $part (@parts) {
                   3334: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3335: 			$all_graded = 0;
                   3336: 		    } else {
                   3337: 			$none_graded = 0;
                   3338: 		    }
                   3339: 		}
                   3340: 
                   3341: 		if ($all_graded || $none_graded) {
                   3342: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3343: 							   $symb,$cdom,$cnum,
                   3344: 							   $udom,$uname);
                   3345: 		}
                   3346: 	    }
                   3347: 
1.126     ng       3348: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3349: 	    $updateCtr++;
1.93      albertel 3350: 	} else {
1.126     ng       3351: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3352: 	    $noupdateCtr++;
1.44      ng       3353: 	}
1.269     raeburn  3354:         if ($aggregateflag) {
                   3355:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3356: 				  $cdom,$cnum);
1.269     raeburn  3357:         }
1.93      albertel 3358:     }
                   3359:     if ($noupdate) {
1.126     ng       3360: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3361: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3362: 	$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       3363:     }
1.72      ng       3364:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3365: 	&show_grading_menu_form ($symb);
1.125     ng       3366:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3367: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3368: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3369:     return $title.$msg.$result;
1.5       albertel 3370: }
1.54      albertel 3371: 
                   3372: sub split_part_type {
                   3373:     my ($partstr) = @_;
                   3374:     my ($temp,@allparts)=split(/_/,$partstr);
                   3375:     my $type=pop(@allparts);
                   3376:     my $part=join('.',@allparts);
                   3377:     return ($part,$type);
                   3378: }
                   3379: 
1.44      ng       3380: #------------- end of section for handling grading by section/class ---------
                   3381: #
                   3382: #----------------------------------------------------------------------------
                   3383: 
1.5       albertel 3384: 
1.44      ng       3385: #----------------------------------------------------------------------------
                   3386: #
                   3387: #-------------------------- Next few routines handles grading by csv upload
                   3388: #
                   3389: #--- Javascript to handle csv upload
1.27      albertel 3390: sub csvupload_javascript_reverse_associate {
1.246     albertel 3391:     my $error1=&mt('You need to specify the username or ID');
                   3392:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3393:   return(<<ENDPICK);
                   3394:   function verify(vf) {
                   3395:     var foundsomething=0;
                   3396:     var founduname=0;
1.243     albertel 3397:     var foundID=0;
1.27      albertel 3398:     for (i=0;i<=vf.nfields.value;i++) {
                   3399:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3400:       if (i==0 && tw!=0) { foundID=1; }
                   3401:       if (i==1 && tw!=0) { founduname=1; }
                   3402:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3403:     }
1.246     albertel 3404:     if (founduname==0 && foundID==0) {
                   3405: 	alert('$error1');
                   3406: 	return;
1.27      albertel 3407:     }
                   3408:     if (foundsomething==0) {
1.246     albertel 3409: 	alert('$error2');
                   3410: 	return;
1.27      albertel 3411:     }
                   3412:     vf.submit();
                   3413:   }
                   3414:   function flip(vf,tf) {
                   3415:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3416:     var i;
                   3417:     for (i=0;i<=vf.nfields.value;i++) {
                   3418:       //can not pick the same destination field for both name and domain
                   3419:       if (((i ==0)||(i ==1)) && 
                   3420:           ((tf==0)||(tf==1)) && 
                   3421:           (i!=tf) &&
                   3422:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3423:         eval('vf.f'+i+'.selectedIndex=0;')
                   3424:       }
                   3425:     }
                   3426:   }
                   3427: ENDPICK
                   3428: }
                   3429: 
                   3430: sub csvupload_javascript_forward_associate {
1.246     albertel 3431:     my $error1=&mt('You need to specify the username or ID');
                   3432:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3433:   return(<<ENDPICK);
                   3434:   function verify(vf) {
                   3435:     var foundsomething=0;
                   3436:     var founduname=0;
1.243     albertel 3437:     var foundID=0;
1.27      albertel 3438:     for (i=0;i<=vf.nfields.value;i++) {
                   3439:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3440:       if (tw==1) { foundID=1; }
                   3441:       if (tw==2) { founduname=1; }
                   3442:       if (tw>3) { foundsomething=1; }
1.27      albertel 3443:     }
1.246     albertel 3444:     if (founduname==0 && foundID==0) {
                   3445: 	alert('$error1');
                   3446: 	return;
1.27      albertel 3447:     }
                   3448:     if (foundsomething==0) {
1.246     albertel 3449: 	alert('$error2');
                   3450: 	return;
1.27      albertel 3451:     }
                   3452:     vf.submit();
                   3453:   }
                   3454:   function flip(vf,tf) {
                   3455:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3456:     var i;
                   3457:     //can not pick the same destination field twice
                   3458:     for (i=0;i<=vf.nfields.value;i++) {
                   3459:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3460:         eval('vf.f'+i+'.selectedIndex=0;')
                   3461:       }
                   3462:     }
                   3463:   }
                   3464: ENDPICK
                   3465: }
                   3466: 
1.26      albertel 3467: sub csvuploadmap_header {
1.324     albertel 3468:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3469:     my $javascript;
1.257     albertel 3470:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3471: 	$javascript=&csvupload_javascript_reverse_associate();
                   3472:     } else {
                   3473: 	$javascript=&csvupload_javascript_forward_associate();
                   3474:     }
1.45      ng       3475: 
1.324     albertel 3476:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3477:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3478:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3479:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3480:     $request->print(<<ENDPICK);
1.26      albertel 3481: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3482: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3483: $result
1.326     albertel 3484: <hr />
1.26      albertel 3485: <h3>Identify fields</h3>
                   3486: Total number of records found in file: $distotal <hr />
                   3487: Enter as many fields as you can. The system will inform you and bring you back
                   3488: to this page if the data selected is insufficient to run your class.<hr />
                   3489: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3490: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3491: <input type="hidden" name="associate"  value="" />
                   3492: <input type="hidden" name="phase"      value="three" />
                   3493: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3494: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3495: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3496: <input type="hidden" name="upfile_associate" 
1.257     albertel 3497:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3498: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3499: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3500: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3501: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3502: <hr />
                   3503: <script type="text/javascript" language="Javascript">
                   3504: $javascript
                   3505: </script>
                   3506: ENDPICK
1.118     ng       3507:     return '';
1.26      albertel 3508: 
                   3509: }
                   3510: 
                   3511: sub csvupload_fields {
1.324     albertel 3512:     my ($symb) = @_;
                   3513:     my (@parts) = &getpartlist($symb);
1.243     albertel 3514:     my @fields=(['ID','Student ID'],
                   3515: 		['username','Student Username'],
                   3516: 		['domain','Student Domain']);
1.324     albertel 3517:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3518:     foreach my $part (sort(@parts)) {
                   3519: 	my @datum;
                   3520: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3521: 	my $name=$part;
                   3522: 	if  (!$display) { $display = $name; }
                   3523: 	@datum=($name,$display);
1.244     albertel 3524: 	if ($name=~/^stores_(.*)_awarded/) {
                   3525: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3526: 	}
1.41      ng       3527: 	push(@fields,\@datum);
                   3528:     }
                   3529:     return (@fields);
1.26      albertel 3530: }
                   3531: 
                   3532: sub csvuploadmap_footer {
1.41      ng       3533:     my ($request,$i,$keyfields) =@_;
                   3534:     $request->print(<<ENDPICK);
1.26      albertel 3535: </table>
                   3536: <input type="hidden" name="nfields" value="$i" />
                   3537: <input type="hidden" name="keyfields" value="$keyfields" />
                   3538: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3539: </form>
                   3540: ENDPICK
                   3541: }
                   3542: 
1.283     albertel 3543: sub checkforfile_js {
1.86      ng       3544:     my $result =<<CSVFORMJS;
                   3545: <script type="text/javascript" language="javascript">
                   3546:     function checkUpload(formname) {
                   3547: 	if (formname.upfile.value == "") {
                   3548: 	    alert("Please use the browse button to select a file from your local directory.");
                   3549: 	    return false;
                   3550: 	}
                   3551: 	formname.submit();
                   3552:     }
                   3553:     </script>
                   3554: CSVFORMJS
1.283     albertel 3555:     return $result;
                   3556: }
                   3557: 
                   3558: sub upcsvScores_form {
                   3559:     my ($request) = shift;
1.324     albertel 3560:     my ($symb)=&get_symb($request);
1.283     albertel 3561:     if (!$symb) {return '';}
                   3562:     my $result=&checkforfile_js();
1.257     albertel 3563:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3564:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3565:     $result.=$table;
1.326     albertel 3566:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3567:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3568:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3569: 	'.</b></td></tr>'."\n";
                   3570:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3571:     my $upload=&mt("Upload Scores");
1.86      ng       3572:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3573:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3574:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3575:     $result.=<<ENDUPFORM;
1.106     albertel 3576: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3577: <input type="hidden" name="symb" value="$symb" />
                   3578: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3579: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3580: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3581: $upfile_select
1.370     www      3582: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3583: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3584: </form>
                   3585: ENDUPFORM
1.370     www      3586:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3587:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3588:     .'</td></tr></table>'."\n";
1.86      ng       3589:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3590:     $result.=&show_grading_menu_form($symb);
1.86      ng       3591:     return $result;
                   3592: }
                   3593: 
                   3594: 
1.26      albertel 3595: sub csvuploadmap {
1.41      ng       3596:     my ($request)= @_;
1.324     albertel 3597:     my ($symb)=&get_symb($request);
1.41      ng       3598:     if (!$symb) {return '';}
1.72      ng       3599: 
1.41      ng       3600:     my $datatoken;
1.257     albertel 3601:     if (!$env{'form.datatoken'}) {
1.41      ng       3602: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3603:     } else {
1.257     albertel 3604: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3605: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3606:     }
1.41      ng       3607:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3608:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3609:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3610:     my ($i,$keyfields);
                   3611:     if (@records) {
1.324     albertel 3612: 	my @fields=&csvupload_fields($symb);
1.45      ng       3613: 
1.257     albertel 3614: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3615: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3616: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3617: 							  \@fields);
                   3618: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3619: 	    chop($keyfields);
                   3620: 	} else {
                   3621: 	    unshift(@fields,['none','']);
                   3622: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3623: 							    \@fields);
1.311     banghart 3624:             foreach my $rec (@records) {
                   3625:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3626:                 if (%temp) {
                   3627:                     $keyfields=join(',',sort(keys(%temp)));
                   3628:                     last;
                   3629:                 }
                   3630:             }
1.41      ng       3631: 	}
                   3632:     }
                   3633:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3634:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3635: 
1.41      ng       3636:     return '';
1.27      albertel 3637: }
                   3638: 
1.246     albertel 3639: sub csvuploadoptions {
1.41      ng       3640:     my ($request)= @_;
1.324     albertel 3641:     my ($symb)=&get_symb($request);
1.257     albertel 3642:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3643:     my $ignore=&mt('Ignore First Line');
                   3644:     $request->print(<<ENDPICK);
                   3645: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3646: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3647: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3648: <!--
1.246     albertel 3649: <p>
                   3650: <label>
                   3651:    <input type="checkbox" name="show_full_results" />
                   3652:    Show a table of all changes
                   3653: </label>
                   3654: </p>
1.302     albertel 3655: -->
1.246     albertel 3656: <p>
                   3657: <label>
                   3658:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3659:    Overwrite any existing score
                   3660: </label>
                   3661: </p>
                   3662: ENDPICK
                   3663:     my %fields=&get_fields();
                   3664:     if (!defined($fields{'domain'})) {
1.257     albertel 3665: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3666: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3667:     }
1.257     albertel 3668:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3669: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3670: 	my $cleankey=$1;
                   3671: 	if ($cleankey eq 'command') { next; }
                   3672: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3673: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3674:     }
                   3675:     # FIXME do a check for any duplicated user ids...
                   3676:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3677:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3678: <hr /></form>'."\n");
1.324     albertel 3679:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3680:     return '';
                   3681: }
                   3682: 
                   3683: sub get_fields {
                   3684:     my %fields;
1.257     albertel 3685:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3686:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3687: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3688: 	    if ($env{'form.f'.$i} ne 'none') {
                   3689: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3690: 	    }
                   3691: 	} else {
1.257     albertel 3692: 	    if ($env{'form.f'.$i} ne 'none') {
                   3693: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3694: 	    }
                   3695: 	}
1.27      albertel 3696:     }
1.246     albertel 3697:     return %fields;
                   3698: }
                   3699: 
                   3700: sub csvuploadassign {
                   3701:     my ($request)= @_;
1.324     albertel 3702:     my ($symb)=&get_symb($request);
1.246     albertel 3703:     if (!$symb) {return '';}
1.345     bowersj2 3704:     my $error_msg = '';
1.246     albertel 3705:     &Apache::loncommon::load_tmp_file($request);
                   3706:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3707:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3708:     my %fields=&get_fields();
1.41      ng       3709:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3710:     my $courseid=$env{'request.course.id'};
1.97      albertel 3711:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3712:     my @notallowed;
1.41      ng       3713:     my @skipped;
                   3714:     my $countdone=0;
                   3715:     foreach my $grade (@gradedata) {
                   3716: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3717: 	my $domain;
                   3718: 	if ($entries{$fields{'domain'}}) {
                   3719: 	    $domain=$entries{$fields{'domain'}};
                   3720: 	} else {
1.257     albertel 3721: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3722: 	}
1.243     albertel 3723: 	$domain=~s/\s//g;
1.41      ng       3724: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3725: 	$username=~s/\s//g;
1.243     albertel 3726: 	if (!$username) {
                   3727: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3728: 	    $id=~s/\s//g;
1.243     albertel 3729: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3730: 	    $username=$ids{$id};
                   3731: 	}
1.41      ng       3732: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3733: 	    my $id=$entries{$fields{'ID'}};
                   3734: 	    $id=~s/\s//g;
                   3735: 	    if ($id) {
                   3736: 		push(@skipped,"$id:$domain");
                   3737: 	    } else {
                   3738: 		push(@skipped,"$username:$domain");
                   3739: 	    }
1.41      ng       3740: 	    next;
                   3741: 	}
1.108     albertel 3742: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3743: 	if (!&canmodify($usec)) {
                   3744: 	    push(@notallowed,"$username:$domain");
                   3745: 	    next;
                   3746: 	}
1.244     albertel 3747: 	my %points;
1.41      ng       3748: 	my %grades;
                   3749: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3750: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3751: 		$dest eq 'domain') { next; }
                   3752: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3753: 	    if ($dest=~/stores_(.*)_points/) {
                   3754: 		my $part=$1;
                   3755: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3756: 					      $symb,$domain,$username);
1.345     bowersj2 3757:                 if ($wgt) {
                   3758:                     $entries{$fields{$dest}}=~s/\s//g;
                   3759:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3760:                     my $award='correct_by_override';
                   3761:                     $grades{"resource.$part.awarded"}=$pcr;
                   3762:                     $grades{"resource.$part.solved"}=$award;
                   3763:                     $points{$part}=1;
                   3764:                 } else {
                   3765:                     $error_msg = "<br />" .
                   3766:                         &mt("Some point values were assigned"
                   3767:                             ." for problems with a weight "
                   3768:                             ."of zero. These values were "
                   3769:                             ."ignored.");
                   3770:                 }
1.244     albertel 3771: 	    } else {
                   3772: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3773: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3774: 		my $store_key=$dest;
                   3775: 		$store_key=~s/^stores/resource/;
                   3776: 		$store_key=~s/_/\./g;
                   3777: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3778: 	    }
1.41      ng       3779: 	}
1.398     albertel 3780: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3781: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.244     albertel 3782: #	&Apache::lonnet::logthis(" storing ".(join('-',%grades)));
1.302     albertel 3783: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3784: 					   $env{'request.course.id'},
                   3785: 					   $domain,$username);
                   3786: 	if ($result eq 'ok') {
                   3787: 	    $request->print('.');
                   3788: 	} else {
                   3789: 	    $request->print("<p>
1.398     albertel 3790:                               <span class=\"LC_error\">
                   3791:                                  Failed to save student $username:$domain.
                   3792:                                  Message when trying to save was ($result)
                   3793:                               </span>
1.302     albertel 3794:                              </p>" );
                   3795: 	}
1.41      ng       3796: 	$request->rflush();
                   3797: 	$countdone++;
                   3798:     }
1.398     albertel 3799:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3800:     if (@skipped) {
1.398     albertel 3801: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3802: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3803:     }
                   3804:     if (@notallowed) {
1.398     albertel 3805: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3806: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3807:     }
1.106     albertel 3808:     $request->print("<br />\n");
1.324     albertel 3809:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3810:     return $error_msg;
1.26      albertel 3811: }
1.44      ng       3812: #------------- end of section for handling csv file upload ---------
                   3813: #
                   3814: #-------------------------------------------------------------------
                   3815: #
1.122     ng       3816: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3817: #
                   3818: #--- Select a page/sequence and a student to grade
1.68      ng       3819: sub pickStudentPage {
                   3820:     my ($request) = shift;
                   3821: 
                   3822:     $request->print(<<LISTJAVASCRIPT);
                   3823: <script type="text/javascript" language="javascript">
                   3824: 
                   3825: function checkPickOne(formname) {
1.76      ng       3826:     if (radioSelection(formname.student) == null) {
1.68      ng       3827: 	alert("Please select the student you wish to grade.");
                   3828: 	return;
                   3829:     }
1.125     ng       3830:     ptr = pullDownSelection(formname.selectpage);
                   3831:     formname.page.value = formname["page"+ptr].value;
                   3832:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3833:     formname.submit();
                   3834: }
                   3835: 
                   3836: </script>
                   3837: LISTJAVASCRIPT
1.118     ng       3838:     &commonJSfunctions($request);
1.324     albertel 3839:     my ($symb) = &get_symb($request);
1.257     albertel 3840:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3841:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3842:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3843: 
1.398     albertel 3844:     my $result='<h3><span class="LC_info">&nbsp;'.
                   3845: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       3846: 
1.80      ng       3847:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3848:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 3849:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 3850:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3851: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3852: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3853:     my $ctr=0;
1.68      ng       3854:     foreach (@$titles) {
                   3855: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3856: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 3857: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       3858: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3859: 	$ctr++;
1.68      ng       3860:     }
1.326     albertel 3861:     $result.= '</select>'."<br />\n";
1.70      ng       3862:     $ctr=0;
                   3863:     foreach (@$titles) {
                   3864: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3865: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3866: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3867: 	$ctr++;
                   3868:     }
1.72      ng       3869:     $result.='<input type="hidden" name="page" />'."\n".
                   3870: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3871: 
1.401     albertel 3872:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 3873: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       3874: 
1.71      ng       3875:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 3876: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 3877: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 3878: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.432   ! banghart 3879:     
        !          3880:     $result.=&build_section_inputs();
        !          3881:     $result.='<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.72      ng       3882: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 3883: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 3884: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       3885: 
1.382     albertel 3886:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   3887: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   3888: 
1.80      ng       3889:     $result.='&nbsp;<input type="button" '.
1.126     ng       3890: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       3891: 
1.68      ng       3892:     $request->print($result);
                   3893: 
1.326     albertel 3894:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       3895: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3896: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       3897: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3898: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       3899: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3900: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       3901:  
1.76      ng       3902:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       3903:     my $ptr = 1;
1.294     albertel 3904:     foreach my $student (sort 
                   3905: 			 {
                   3906: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3907: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3908: 			     }
                   3909: 			     return $a cmp $b;
                   3910: 			 } (keys(%$fullname))) {
1.68      ng       3911: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       3912: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   3913: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 3914: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   3915: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       3916: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       3917: 	$ptr++;
                   3918:     }
1.381     albertel 3919:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   3920:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       3921:     $studentTable.='<input type="button" '.
                   3922: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       3923: 
1.324     albertel 3924:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       3925:     $request->print($studentTable);
                   3926: 
                   3927:     return '';
                   3928: }
                   3929: 
                   3930: sub getSymbMap {
1.132     bowersj2 3931:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       3932: 
                   3933:     my %symbx = ();
                   3934:     my @titles = ();
1.117     bowersj2 3935:     my $minder = 0;
                   3936: 
                   3937:     # Gather every sequence that has problems.
1.240     albertel 3938:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   3939: 					       1,0,1);
1.117     bowersj2 3940:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 3941: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 3942: 	    my $title = $minder.'.'.
                   3943: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   3944: 	    push(@titles, $title); # minder in case two titles are identical
                   3945: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 3946: 	    $minder++;
1.241     albertel 3947: 	}
1.68      ng       3948:     }
                   3949:     return \@titles,\%symbx;
                   3950: }
                   3951: 
1.72      ng       3952: #
                   3953: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       3954: sub displayPage {
                   3955:     my ($request) = shift;
                   3956: 
1.324     albertel 3957:     my ($symb) = &get_symb($request);
1.257     albertel 3958:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3959:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3960:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3961:     my $pageTitle = $env{'form.page'};
1.103     albertel 3962:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 3963:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   3964:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 3965: 
                   3966:     #need to make sure we have the correct data for later EXT calls, 
                   3967:     #thus invalidate the cache
                   3968:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3969:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3970:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3971:     &Apache::lonnet::clear_EXT_cache_status();
                   3972: 
1.103     albertel 3973:     if (!&canview($usec)) {
1.398     albertel 3974: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 3975: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 3976: 	return;
                   3977:     }
1.398     albertel 3978:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 3979:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       3980: 	'</h3>'."\n";
1.382     albertel 3981:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   3982: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   3983:     } else {
                   3984: 	delete($env{'form.CODE'});
                   3985:     }
1.71      ng       3986:     &sub_page_js($request);
                   3987:     $request->print($result);
                   3988: 
1.132     bowersj2 3989:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 3990:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       3991:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 3992:     if (!$map) {
1.398     albertel 3993: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 3994: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 3995: 	return; 
                   3996:     }
1.68      ng       3997:     my $iterator = $navmap->getIterator($map->map_start(),
                   3998: 					$map->map_finish());
                   3999: 
1.71      ng       4000:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4001: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4002: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4003: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4004: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4005: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4006: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4007: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4008: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4009: 
1.382     albertel 4010:     if (defined($env{'form.CODE'})) {
                   4011: 	$studentTable.=
                   4012: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4013:     }
1.381     albertel 4014:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4015: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4016: 	'/check.gif" height="16" border="0" />';
                   4017: 
1.118     ng       4018:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4019: 	' symbol.'."\n".
1.71      ng       4020: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4021: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4022: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4023: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4024: 
1.329     albertel 4025:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4026:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4027:     $iterator->next(); # skip the first BEGIN_MAP
                   4028:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4029:     while ($depth > 0) {
1.68      ng       4030:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4031:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4032: 
1.385     albertel 4033:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4034: 	    my $parts = $curRes->parts();
1.68      ng       4035:             my $title = $curRes->compTitle();
1.71      ng       4036: 	    my $symbx = $curRes->symb();
1.196     albertel 4037: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4038: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4039: 	    $studentTable.='<td valign="top">';
1.382     albertel 4040: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4041: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4042: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4043: 					     undef,'both',\%form);
1.71      ng       4044: 	    } else {
1.382     albertel 4045: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4046: 		$companswer =~ s|<form(.*?)>||g;
                   4047: 		$companswer =~ s|</form>||g;
1.71      ng       4048: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4049: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4050: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4051: #		}
1.116     ng       4052: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4053: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4054: 	    }
                   4055: 
1.257     albertel 4056: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4057: 
1.257     albertel 4058: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4059: 		if ($record{'version'} eq '') {
1.398     albertel 4060: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4061: 		} else {
1.116     ng       4062: 		    my %responseType = ();
                   4063: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4064: 			my @responseIds =$curRes->responseIds($partid);
                   4065: 			my @responseType =$curRes->responseType($partid);
                   4066: 			my %responseIds;
                   4067: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4068: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4069: 			}
                   4070: 			$responseType{$partid} = \%responseIds;
1.116     ng       4071: 		    }
1.148     albertel 4072: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4073: 
1.71      ng       4074: 		}
1.257     albertel 4075: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4076: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4077: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4078: 									$env{'request.course.id'},
1.71      ng       4079: 									'','.submission');
                   4080:  
                   4081: 	    }
1.103     albertel 4082: 	    if (&canmodify($usec)) {
                   4083: 		foreach my $partid (@{$parts}) {
                   4084: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4085: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4086: 		    $question++;
                   4087: 		}
1.196     albertel 4088: 		$prob++;
1.71      ng       4089: 	    }
                   4090: 	    $studentTable.='</td></tr>';
1.68      ng       4091: 
1.103     albertel 4092: 	}
1.68      ng       4093:         $curRes = $iterator->next();
                   4094:     }
                   4095: 
1.381     albertel 4096:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4097: 	'<input type="button" value="Save" '.
1.381     albertel 4098: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4099: 	'</form>'."\n";
1.324     albertel 4100:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4101:     $request->print($studentTable);
                   4102: 
                   4103:     return '';
1.119     ng       4104: }
                   4105: 
                   4106: sub displaySubByDates {
1.148     albertel 4107:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4108:     my $isCODE=0;
1.335     albertel 4109:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4110:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4111:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4112: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4113: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4114: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4115: 	'<td><b>Submission</b></td>'.
                   4116: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4117:     my ($version);
                   4118:     my %mark;
1.148     albertel 4119:     my %orders;
1.119     ng       4120:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4121:     if (!exists($$record{'1:timestamp'})) {
1.398     albertel 4122: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
1.147     albertel 4123:     }
1.335     albertel 4124: 
                   4125:     my $interaction;
1.119     ng       4126:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4127: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4128: 	if (exists($$record{$version.':resource.0.version'})) {
                   4129: 	    $interaction = $$record{$version.':resource.0.version'};
                   4130: 	}
                   4131: 
                   4132: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4133: 		             : "$version:resource");
                   4134: 	#&Apache::lonnet::logthis(" got $where");
1.119     ng       4135: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4136: 	if ($isCODE) {
                   4137: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4138: 	}
1.119     ng       4139: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4140: 	my @displaySub = ();
                   4141: 	foreach my $partid (@{$parts}) {
1.335     albertel 4142: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4143: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4144: 	    
                   4145: 
1.122     ng       4146: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4147: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4148: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4149: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4150: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4151: 
                   4152: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4153: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   4154: 		    #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
1.207     albertel 4155: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.398     albertel 4156: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
                   4157: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4158: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4159: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4160: 		    } else {
                   4161: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4162: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4163: 		    }
1.335     albertel 4164: 		    my $responseType=($isTask ? 'Task'
                   4165:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4166: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4167: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4168: 			$orders{$partid}->{$responseId}=
                   4169: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4170: 		    }
1.147     albertel 4171: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4172: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4173: 		}
                   4174: 	    }
1.335     albertel 4175: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4176: 		$displaySub[1].='Checked in by '.
                   4177: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4178: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4179: 		    '<br />';
                   4180: 	    }
                   4181: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4182: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4183: 		    lc($$record{"$where.$partid.award"}).' '.
                   4184: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4185: 		    '<br />';
                   4186: 	    }
1.335     albertel 4187: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4188: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4189: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4190: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4191: 		$displaySub[2].=
                   4192: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4193: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4194: 	    }
                   4195: 	}
                   4196: 	# needed because old essay regrader has not parts info
                   4197: 	if (exists $$record{"$version:resource.regrader"}) {
                   4198: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4199: 	}
                   4200: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4201: 	if ($displaySub[2]) {
                   4202: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4203: 	}
1.382     albertel 4204: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4205:     
1.119     ng       4206:     }
                   4207:     $studentTable.='</table></td></tr></table>';
                   4208:     return $studentTable;
1.71      ng       4209: }
                   4210: 
                   4211: sub updateGradeByPage {
                   4212:     my ($request) = shift;
                   4213: 
1.257     albertel 4214:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4215:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4216:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4217:     my $pageTitle = $env{'form.page'};
1.103     albertel 4218:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4219:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4220:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4221:     if (!&canmodify($usec)) {
1.398     albertel 4222: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4223: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4224: 	return;
                   4225:     }
1.398     albertel 4226:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4227:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4228: 	'</h3>'."\n";
1.70      ng       4229: 
1.68      ng       4230:     $request->print($result);
                   4231: 
1.132     bowersj2 4232:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4233:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4234:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4235:     if (!$map) {
1.398     albertel 4236: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4237: 	my ($symb)=&get_symb($request);
                   4238: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4239: 	return; 
                   4240:     }
1.71      ng       4241:     my $iterator = $navmap->getIterator($map->map_start(),
                   4242: 					$map->map_finish());
1.70      ng       4243: 
1.71      ng       4244:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4245: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4246: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4247: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4248: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4249: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4250: 
                   4251:     $iterator->next(); # skip the first BEGIN_MAP
                   4252:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4253:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4254:     while ($depth > 0) {
1.71      ng       4255:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4256:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4257: 
1.385     albertel 4258:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4259: 	    my $parts = $curRes->parts();
1.71      ng       4260:             my $title = $curRes->compTitle();
                   4261: 	    my $symbx = $curRes->symb();
1.196     albertel 4262: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4263: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4264: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4265: 
                   4266: 	    my %newrecord=();
                   4267: 	    my @displayPts=();
1.269     raeburn  4268:             my %aggregate = ();
                   4269:             my $aggregateflag = 0;
1.71      ng       4270: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4271: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4272: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4273: 
1.257     albertel 4274: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4275: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4276: 		my $partial = $newpts/$wgt;
                   4277: 		my $score;
                   4278: 		if ($partial > 0) {
                   4279: 		    $score = 'correct_by_override';
1.125     ng       4280: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4281: 		    $score = 'incorrect_by_override';
                   4282: 		}
1.257     albertel 4283: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4284: 		if ($dropMenu eq 'excused') {
1.71      ng       4285: 		    $partial = '';
                   4286: 		    $score = 'excused';
1.125     ng       4287: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4288: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4289: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4290: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4291: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4292: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4293: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4294: 		    $changeflag++;
                   4295: 		    $newpts = '';
1.269     raeburn  4296:                     
                   4297:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4298:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4299:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4300:                     if ($aggtries > 0) {
                   4301:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4302:                         $aggregateflag = 1;
                   4303:                     }
1.71      ng       4304: 		}
1.324     albertel 4305: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4306: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4307: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4308: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4309: 		    '&nbsp;<br />';
1.207     albertel 4310: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4311: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4312: 		    '&nbsp;<br />';
1.71      ng       4313: 		$question++;
1.380     albertel 4314: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4315: 
1.71      ng       4316: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4317: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4318: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4319: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4320: 
                   4321: 		$changeflag++;
                   4322: 	    }
                   4323: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4324: 		my %record = 
                   4325: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4326: 					     $udom,$uname);
                   4327: 
                   4328: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4329: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4330: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4331: 		    $newrecord{'resource.CODE'} = '';
                   4332: 		}
1.257     albertel 4333: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4334: 					$udom,$uname);
1.382     albertel 4335: 		%record = &Apache::lonnet::restore($symbx,
                   4336: 						   $env{'request.course.id'},
                   4337: 						   $udom,$uname);
1.380     albertel 4338: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4339: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4340: 	    }
1.380     albertel 4341: 	    
1.269     raeburn  4342:             if ($aggregateflag) {
                   4343:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4344:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4345:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4346:             }
1.125     ng       4347: 
1.71      ng       4348: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4349: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4350: 		'</tr>';
1.68      ng       4351: 
1.196     albertel 4352: 	    $prob++;
1.68      ng       4353: 	}
1.71      ng       4354:         $curRes = $iterator->next();
1.68      ng       4355:     }
1.98      albertel 4356: 
1.71      ng       4357:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4358:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4359:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4360: 		  'The scores were changed for '.
                   4361: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4362:     $request->print($grademsg.$studentTable);
1.68      ng       4363: 
1.70      ng       4364:     return '';
                   4365: }
                   4366: 
1.72      ng       4367: #-------- end of section for handling grading by page/sequence ---------
                   4368: #
                   4369: #-------------------------------------------------------------------
                   4370: 
1.75      albertel 4371: #--------------------Scantron Grading-----------------------------------
                   4372: #
                   4373: #------ start of section for handling grading by page/sequence ---------
                   4374: 
1.423     albertel 4375: =pod
                   4376: 
                   4377: =head1 Bubble sheet grading routines
                   4378: 
1.424     albertel 4379:   For this documentation:
                   4380: 
                   4381:    'scanline' refers to the full line of characters
                   4382:    from the file that we are parsing that represents one entire sheet
                   4383: 
                   4384:    'bubble line' refers to the data
                   4385:    representing the line of bubbles that are on the physical bubble sheet
                   4386: 
                   4387: 
                   4388: The overall process is that a scanned in bubble sheet data is uploaded
                   4389: into a course. When a user wants to grade, they select a
                   4390: sequence/folder of resources, a file of bubble sheet info, and pick
                   4391: one of the predefined configurations for what each scanline looks
                   4392: like.
                   4393: 
                   4394: Next each scanline is checked for any errors of either 'missing
                   4395: bubbles' (it's an error because it may have been missed scanned
                   4396: because too light bubbling), 'double bubble' (each bubble line should
                   4397: have no more that one letter picked), invalid or duplicated CODE,
                   4398: invalid student ID
                   4399: 
                   4400: If the CODE option is used that determines the randomization of the
                   4401: homework problems, either way the student ID is looked up into a
                   4402: username:domain.
                   4403: 
                   4404: During the validation phase the instructor can choose to skip scanlines. 
                   4405: 
                   4406: After the validation phase, there is now 3 bubble sheet files
                   4407: 
                   4408:   scantron_original_filename (unmodified original file)
                   4409:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4410:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4411: 
                   4412: Also there is a separate hash nohist_scantrondata that contains extra
                   4413: correction information that isn't representable in the bubble sheet
                   4414: file (see &scantron_getfile() for more information)
                   4415: 
                   4416: After all scanlines are either valid, marked as valid or skipped, then
                   4417: foreach line foreach problem in the picked sequence, an ssi request is
                   4418: made that simulates a user submitting their selected letter(s) against
                   4419: the homework problem.
1.423     albertel 4420: 
                   4421: =over 4
                   4422: 
                   4423: =cut
                   4424: 
                   4425: 
                   4426: =pod 
                   4427: 
                   4428: =item defaultFormData
                   4429: 
                   4430:   Returns html hidden inputs used to hold context/default values.
                   4431: 
                   4432:  Arguments:
                   4433:   $symb - $symb of the current resource 
                   4434: 
                   4435: =cut
1.422     foxr     4436: 
1.81      albertel 4437: sub defaultFormData {
1.324     albertel 4438:     my ($symb)=@_;
1.81      albertel 4439:     return '
1.418     albertel 4440:       <input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4441:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4442:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4443: }
                   4444: 
1.423     albertel 4445: =pod 
                   4446: 
                   4447: =item getSequenceDropDown
                   4448: 
                   4449:    Return html dropdown of possible sequences to grade
                   4450:  
                   4451:  Arguments:
                   4452:    $symb - $symb of the current resource 
                   4453: 
                   4454: =cut
1.422     foxr     4455: 
1.75      albertel 4456: sub getSequenceDropDown {
1.423     albertel 4457:     my ($symb)=@_;
1.75      albertel 4458:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4459:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4460:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4461:     my $ctr=0;
                   4462:     foreach (@$titles) {
                   4463: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4464: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4465: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4466: 	    '>'.$showtitle.'</option>'."\n";
                   4467: 	$ctr++;
                   4468:     }
                   4469:     $result.= '</select>';
                   4470:     return $result;
                   4471: }
                   4472: 
1.423     albertel 4473: 
                   4474: =pod 
                   4475: 
                   4476: =item scantron_filenames
                   4477: 
                   4478:    Returns a list of the scantron files in the current course 
                   4479: 
                   4480: =cut
1.422     foxr     4481: 
1.202     albertel 4482: sub scantron_filenames {
1.257     albertel 4483:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4484:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4485:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4486: 				    &propath($cdom,$cname));
1.202     albertel 4487:     my @possiblenames;
1.201     albertel 4488:     foreach my $filename (sort(@files)) {
1.157     albertel 4489: 	($filename)=split(/&/,$filename);
                   4490: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4491: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4492: 	push(@possiblenames,$filename);
                   4493:     }
                   4494:     return @possiblenames;
                   4495: }
                   4496: 
1.423     albertel 4497: =pod 
                   4498: 
                   4499: =item scantron_uploads
                   4500: 
                   4501:    Returns  html drop-down list of scantron files in current course.
                   4502: 
                   4503:  Arguments:
                   4504:    $file2grade - filename to set as selected in the dropdown
                   4505: 
                   4506: =cut
1.422     foxr     4507: 
1.202     albertel 4508: sub scantron_uploads {
1.209     ng       4509:     my ($file2grade) = @_;
1.202     albertel 4510:     my $result=	'<select name="scantron_selectfile">';
                   4511:     $result.="<option></option>";
                   4512:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4513: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4514:     }
                   4515:     $result.="</select>";
                   4516:     return $result;
                   4517: }
                   4518: 
1.423     albertel 4519: =pod 
                   4520: 
                   4521: =item scantron_scantab
                   4522: 
                   4523:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4524:   file.
                   4525: 
                   4526: =cut
1.422     foxr     4527: 
1.82      albertel 4528: sub scantron_scantab {
                   4529:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4530:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4531:     $result.='<option></option>'."\n";
1.82      albertel 4532:     foreach my $line (<$fh>) {
                   4533: 	my ($name,$descrip)=split(/:/,$line);
                   4534: 	if ($name =~ /^\#/) { next; }
                   4535: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4536:     }
                   4537:     $result.='</select>'."\n";
                   4538: 
                   4539:     return $result;
                   4540: }
                   4541: 
1.423     albertel 4542: =pod 
                   4543: 
                   4544: =item scantron_CODElist
                   4545: 
                   4546:   Returns html drop down of the saved CODE lists from current course,
                   4547:   generated from earlier printings.
                   4548: 
                   4549: =cut
1.422     foxr     4550: 
1.186     albertel 4551: sub scantron_CODElist {
1.257     albertel 4552:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4553:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4554:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4555:     my $namechoice='<option></option>';
1.225     albertel 4556:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4557: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4558: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4559: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4560:     }
                   4561:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4562:     return $namechoice;
                   4563: }
                   4564: 
1.423     albertel 4565: =pod 
                   4566: 
                   4567: =item scantron_CODEunique
                   4568: 
                   4569:   Returns the html for "Each CODE to be used once" radio.
                   4570: 
                   4571: =cut
1.422     foxr     4572: 
1.186     albertel 4573: sub scantron_CODEunique {
1.381     albertel 4574:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4575:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4576:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4577:                 </span>
                   4578:                 <span style="white-space: nowrap;">
1.272     albertel 4579:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4580:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4581:                 </span>';
1.186     albertel 4582:     return $result;
                   4583: }
1.423     albertel 4584: 
                   4585: =pod 
                   4586: 
                   4587: =item scantron_selectphase
                   4588: 
                   4589:   Generates the initial screen to start the bubble sheet process.
                   4590:   Allows for - starting a grading run.
1.424     albertel 4591:              - downloading existing scan data (original, corrected
1.423     albertel 4592:                                                 or skipped info)
                   4593: 
                   4594:              - uploading new scan data
                   4595: 
                   4596:  Arguments:
                   4597:   $r          - The Apache request object
                   4598:   $file2grade - name of the file that contain the scanned data to score
                   4599: 
                   4600: =cut
1.186     albertel 4601: 
1.75      albertel 4602: sub scantron_selectphase {
1.209     ng       4603:     my ($r,$file2grade) = @_;
1.324     albertel 4604:     my ($symb)=&get_symb($r);
1.75      albertel 4605:     if (!$symb) {return '';}
1.423     albertel 4606:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4607:     my $default_form_data=&defaultFormData($symb);
                   4608:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4609:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4610:     my $format_selector=&scantron_scantab();
1.186     albertel 4611:     my $CODE_selector=&scantron_CODElist();
                   4612:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4613:     my $result;
1.422     foxr     4614: 
                   4615:     # Chunk of form to prompt for a file to grade and how:
                   4616: 
1.75      albertel 4617:     $result.= <<SCANTRONFORM;
1.162     albertel 4618:     <table width="100%" border="0">
1.75      albertel 4619:     <tr>
1.226     albertel 4620:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4621:       <td bgcolor="#777777">
1.203     albertel 4622:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4623:         $default_form_data
1.75      albertel 4624:         <table width="100%" border="0">
                   4625:           <tr bgcolor="#e6ffff">
1.174     albertel 4626:             <td colspan="2">
                   4627:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4628:             </td>
                   4629:           </tr>
                   4630:           <tr bgcolor="#ffffe6">
1.174     albertel 4631:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4632:           </tr>
                   4633:           <tr bgcolor="#ffffe6">
1.174     albertel 4634:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4635:           </tr>
1.82      albertel 4636:           <tr bgcolor="#ffffe6">
1.174     albertel 4637:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4638:           </tr>
1.157     albertel 4639:           <tr bgcolor="#ffffe6">
1.186     albertel 4640:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4641:           </tr>
                   4642:           <tr bgcolor="#ffffe6">
                   4643:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4644:           </tr>
                   4645:           <tr bgcolor="#ffffe6">
1.187     albertel 4646: 	    <td> Options: </td>
                   4647:             <td>
1.272     albertel 4648: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4649:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4650:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4651: 	    </td>
                   4652:           </tr>
                   4653:           <tr bgcolor="#ffffe6">
1.174     albertel 4654:             <td colspan="2">
1.265     www      4655:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4656:             </td>
                   4657:           </tr>
                   4658:         </table>
1.226     albertel 4659:        </td>
                   4660:      </form>
1.162     albertel 4661:     </tr>
                   4662: SCANTRONFORM
                   4663:    
                   4664:     $r->print($result);
                   4665: 
1.257     albertel 4666:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4667:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4668: 
1.422     foxr     4669: 	# Chunk of form to prompt for a scantron file upload.
                   4670: 
1.162     albertel 4671:         $r->print(<<SCANTRONFORM);
                   4672:     <tr>
                   4673:       <td bgcolor="#777777">
                   4674:         <table width="100%" border="0">
                   4675:           <tr bgcolor="#e6ffff">
                   4676:             <td>
1.174     albertel 4677:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4678:             </td>
                   4679:           </tr>
                   4680:           <tr bgcolor="#ffffe6">
                   4681:             <td>
                   4682: SCANTRONFORM
1.324     albertel 4683:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4684:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4685:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4686:     $r->print(<<UPLOAD);
                   4687:               <script type="text/javascript" language="javascript">
                   4688:     function checkUpload(formname) {
                   4689: 	if (formname.upfile.value == "") {
                   4690: 	    alert("Please use the browse button to select a file from your local directory.");
                   4691: 	    return false;
                   4692: 	}
                   4693: 	formname.submit();
                   4694:     }
                   4695:               </script>
                   4696: 
                   4697:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4698:                 $default_form_data
                   4699:                 <input name='courseid' type='hidden' value='$cnum' />
                   4700:                 <input name='domainid' type='hidden' value='$cdom' />
                   4701:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4702:                 File to upload:<input type="file" name="upfile" size="50" />
                   4703:                 <br />
                   4704:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4705:               </form>
                   4706: UPLOAD
1.162     albertel 4707: 
                   4708:         $r->print(<<SCANTRONFORM);
                   4709:             </td>
                   4710:           </tr>
1.75      albertel 4711:         </table>
                   4712:       </td>
                   4713:     </tr>
1.162     albertel 4714: SCANTRONFORM
                   4715:     }
1.422     foxr     4716: 
                   4717:     # Chunk of the form that prompts to view a scoring office file,
                   4718:     # corrected file, skipped records in a file.
                   4719: 
1.187     albertel 4720:     $r->print(<<SCANTRONFORM);
                   4721:     <tr>
1.226     albertel 4722:       <form action='/adm/grades' name='scantron_download'>
                   4723:         <td bgcolor="#777777">
1.379     albertel 4724: 	  $default_form_data
1.187     albertel 4725:           <input type="hidden" name="command" value="scantron_download" />
                   4726:           <table width="100%" border="0">
                   4727:             <tr bgcolor="#e6ffff">
                   4728:               <td colspan="2">
                   4729:                 &nbsp;<b>Download a scoring office file</b>
                   4730:               </td>
                   4731:             </tr>
                   4732:             <tr bgcolor="#ffffe6">
                   4733:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4734:             </tr>
                   4735:             <tr bgcolor="#ffffe6">
                   4736:               <td colspan="2">
1.293     www      4737:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4738:               </td>
                   4739:             </tr>
                   4740:           </table>
1.226     albertel 4741:         </td>
                   4742:       </form>
1.187     albertel 4743:     </tr>
                   4744: SCANTRONFORM
1.162     albertel 4745: 
                   4746:     $r->print(<<SCANTRONFORM);
1.75      albertel 4747:   </table>
1.81      albertel 4748: $grading_menu_button
1.75      albertel 4749: SCANTRONFORM
                   4750: 
1.162     albertel 4751:     return
1.75      albertel 4752: }
                   4753: 
1.423     albertel 4754: =pod
                   4755: 
                   4756: =item get_scantron_config
                   4757: 
                   4758:    Parse and return the scantron configuration line selected as a
                   4759:    hash of configuration file fields.
                   4760: 
                   4761:  Arguments:
                   4762:     which - the name of the configuration to parse from the file.
                   4763: 
                   4764: 
                   4765:  Returns:
                   4766:             If the named configuration is not in the file, an empty
                   4767:             hash is returned.
                   4768:     a hash with the fields
                   4769:       name         - internal name for the this configuration setup
                   4770:       description  - text to display to operator that describes this config
                   4771:       CODElocation - if 0 or the string 'none'
                   4772:                           - no CODE exists for this config
                   4773:                      if -1 || the string 'letter'
                   4774:                           - a CODE exists for this config and is
                   4775:                             a string of letters
                   4776:                      Unsupported value (but planned for future support)
                   4777:                           if a positive integer
                   4778:                                - The CODE exists as the first n items from
                   4779:                                  the question section of the form
                   4780:                           if the string 'number'
                   4781:                                - The CODE exists for this config and is
                   4782:                                  a string of numbers
                   4783:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4784:                      the CODE starts
                   4785:       CODElength  - length of the CODE
                   4786:       IDstart     - column where the student ID number starts
                   4787:       IDlength    - length of the student ID info
                   4788:       Qstart      - column where the information from the bubbled
                   4789:                     'questions' start
                   4790:       Qlength     - number of columns comprising a single bubble line from
                   4791:                     the sheet. (usually either 1 or 10)
1.424     albertel 4792:       Qon         - either a single character representing the character used
1.423     albertel 4793:                     to signal a bubble was chosen in the positional setup, or
                   4794:                     the string 'letter' if the letter of the chosen bubble is
                   4795:                     in the final, or 'number' if a number representing the
                   4796:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 4797:       Qoff        - the character used to represent that a bubble was
                   4798:                     left blank
1.423     albertel 4799:       PaperID     - if the scanning process generates a unique number for each
                   4800:                     sheet scanned the column that this ID number starts in
                   4801:       PaperIDlength - number of columns that comprise the unique ID number
                   4802:                       for the sheet of paper
1.424     albertel 4803:       FirstName   - column that the first name starts in
1.423     albertel 4804:       FirstNameLength - number of columns that the first name spans
                   4805:  
                   4806:       LastName    - column that the last name starts in
                   4807:       LastNameLength - number of columns that the last name spans
                   4808: 
                   4809: =cut
1.422     foxr     4810: 
1.82      albertel 4811: sub get_scantron_config {
                   4812:     my ($which) = @_;
                   4813:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4814:     my %config;
1.157     albertel 4815:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4816:     foreach my $line (<$fh>) {
                   4817: 	my ($name,$descrip)=split(/:/,$line);
                   4818: 	if ($name ne $which ) { next; }
                   4819: 	chomp($line);
                   4820: 	my @config=split(/:/,$line);
                   4821: 	$config{'name'}=$config[0];
                   4822: 	$config{'description'}=$config[1];
                   4823: 	$config{'CODElocation'}=$config[2];
                   4824: 	$config{'CODEstart'}=$config[3];
                   4825: 	$config{'CODElength'}=$config[4];
                   4826: 	$config{'IDstart'}=$config[5];
                   4827: 	$config{'IDlength'}=$config[6];
                   4828: 	$config{'Qstart'}=$config[7];
                   4829: 	$config{'Qlength'}=$config[8];
                   4830: 	$config{'Qoff'}=$config[9];
                   4831: 	$config{'Qon'}=$config[10];
1.157     albertel 4832: 	$config{'PaperID'}=$config[11];
                   4833: 	$config{'PaperIDlength'}=$config[12];
                   4834: 	$config{'FirstName'}=$config[13];
                   4835: 	$config{'FirstNamelength'}=$config[14];
                   4836: 	$config{'LastName'}=$config[15];
                   4837: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4838: 	last;
                   4839:     }
                   4840:     return %config;
                   4841: }
                   4842: 
1.423     albertel 4843: =pod 
                   4844: 
                   4845: =item username_to_idmap
                   4846: 
                   4847:     creates a hash keyed by student id with values of the corresponding
                   4848:     student username:domain.
                   4849: 
                   4850:   Arguments:
                   4851: 
                   4852:     $classlist - reference to the class list hash. This is a hash
                   4853:                  keyed by student name:domain  whose elements are references
1.424     albertel 4854:                  to arrays containing various chunks of information
1.423     albertel 4855:                  about the student. (See loncoursedata for more info).
                   4856: 
                   4857:   Returns
                   4858:     %idmap - the constructed hash
                   4859: 
                   4860: =cut
                   4861: 
1.82      albertel 4862: sub username_to_idmap {
                   4863:     my ($classlist)= @_;
                   4864:     my %idmap;
                   4865:     foreach my $student (keys(%$classlist)) {
                   4866: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4867: 	    $student;
                   4868:     }
                   4869:     return %idmap;
                   4870: }
1.423     albertel 4871: 
                   4872: =pod
                   4873: 
1.424     albertel 4874: =item scantron_fixup_scanline
1.423     albertel 4875: 
                   4876:    Process a requested correction to a scanline.
                   4877: 
                   4878:   Arguments:
                   4879:     $scantron_config   - hash from &get_scantron_config()
                   4880:     $scan_data         - hash of correction information 
                   4881:                           (see &scantron_getfile())
                   4882:     $line              - existing scanline
                   4883:     $whichline         - line number of the passed in scanline
                   4884:     $field             - type of change to process 
                   4885:                          (either 
                   4886:                           'ID'     -> correct the student ID number
                   4887:                           'CODE'   -> correct the CODE
                   4888:                           'answer' -> fixup the submitted answers)
                   4889:     
                   4890:    $args               - hash of additional info,
                   4891:                           - 'ID' 
                   4892:                                'newid' -> studentID to use in replacement
1.424     albertel 4893:                                           of existing one
1.423     albertel 4894:                           - 'CODE' 
                   4895:                                'CODE_ignore_dup' - set to true if duplicates
                   4896:                                                    should be ignored.
                   4897: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 4898:                                         if the existing unfound code should
1.423     albertel 4899:                                         be used as is
                   4900:                           - 'answer'
                   4901:                                'response' - new answer or 'none' if blank
                   4902:                                'question' - the bubble line to change
                   4903: 
                   4904:   Returns:
                   4905:     $line - the modified scanline
                   4906: 
                   4907:   Side effects: 
                   4908:     $scan_data - may be updated
                   4909: 
                   4910: =cut
                   4911: 
1.82      albertel 4912: 
1.157     albertel 4913: sub scantron_fixup_scanline {
                   4914:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.423     albertel 4915: 
1.157     albertel 4916:     if ($field eq 'ID') {
                   4917: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 4918: 	    return ($line,1,'New value too large');
1.157     albertel 4919: 	}
                   4920: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   4921: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   4922: 				     $args->{'newid'});
                   4923: 	}
                   4924: 	substr($line,$$scantron_config{'IDstart'}-1,
                   4925: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   4926: 	if ($args->{'newid'}=~/^\s*$/) {
                   4927: 	    &scan_data($scan_data,"$whichline.user",
                   4928: 		       $args->{'username'}.':'.$args->{'domain'});
                   4929: 	}
1.186     albertel 4930:     } elsif ($field eq 'CODE') {
1.192     albertel 4931: 	if ($args->{'CODE_ignore_dup'}) {
                   4932: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   4933: 	}
                   4934: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   4935: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 4936: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   4937: 		return ($line,1,'New CODE value too large');
                   4938: 	    }
                   4939: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   4940: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   4941: 	    }
                   4942: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   4943: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 4944: 	}
1.157     albertel 4945:     } elsif ($field eq 'answer') {
                   4946: 	my $length=$scantron_config->{'Qlength'};
                   4947: 	my $off=$scantron_config->{'Qoff'};
                   4948: 	my $on=$scantron_config->{'Qon'};
                   4949: 	my $answer=${off}x$length;
                   4950: 	if ($args->{'response'} eq 'none') {
                   4951: 	    &scan_data($scan_data,
                   4952: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   4953: 	} else {
1.274     albertel 4954: 	    if ($on eq 'letter') {
                   4955: 		my @alphabet=('A'..'Z');
                   4956: 		$answer=$alphabet[$args->{'response'}];
                   4957: 	    } elsif ($on eq 'number') {
                   4958: 		$answer=$args->{'response'}+1;
1.389     albertel 4959: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 4960: 	    } else {
                   4961: 		substr($answer,$args->{'response'},1)=$on;
                   4962: 	    }
1.157     albertel 4963: 	    &scan_data($scan_data,
                   4964: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   4965: 	}
                   4966: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   4967: 	substr($line,$where-1,$length)=$answer;
                   4968:     }
                   4969:     return $line;
                   4970: }
1.423     albertel 4971: 
                   4972: =pod
                   4973: 
                   4974: =item scan_data
                   4975: 
                   4976:     Edit or look up  an item in the scan_data hash.
                   4977: 
                   4978:   Arguments:
                   4979:     $scan_data  - The hash (see scantron_getfile)
                   4980:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 4981:                   scantronfilename_key).
1.423     albertel 4982:     $data        - New value of the hash entry.
                   4983:     $delete      - If true, the entry is removed from the hash.
                   4984: 
                   4985:   Returns:
                   4986:     The new value of the hash table field (undefined if deleted).
                   4987: 
                   4988: =cut
                   4989: 
                   4990: 
1.157     albertel 4991: sub scan_data {
                   4992:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 4993:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 4994:     if (defined($value)) {
                   4995: 	$scan_data->{$filename.'_'.$key} = $value;
                   4996:     }
                   4997:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   4998:     return $scan_data->{$filename.'_'.$key};
                   4999: }
1.423     albertel 5000: 
                   5001: =pod 
                   5002: 
                   5003: =item scantron_parse_scanline
                   5004: 
                   5005:   Decodes a scanline from the selected scantron file
                   5006: 
                   5007:  Arguments:
                   5008:     line             - The text of the scantron file line to process
                   5009:     whichline        - Line number
                   5010:     scantron_config  - Hash describing the format of the scantron lines.
                   5011:     scan_data        - Hash of extra information about the scanline
                   5012:                        (see scantron_getfile for more information)
                   5013:     just_header      - True if should not process question answers but only
                   5014:                        the stuff to the left of the answers.
                   5015:  Returns:
                   5016:    Hash containing the result of parsing the scanline
                   5017: 
                   5018:    Keys are all proceeded by the string 'scantron.'
                   5019: 
                   5020:        CODE    - the CODE in use for this scanline
                   5021:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5022:                  by the operator
                   5023:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5024:                             CODEs were selected, but the usage has been
                   5025:                             forced by the operator
                   5026:        ID  - student ID
                   5027:        PaperID - if used, the ID number printed on the sheet when the 
                   5028:                  paper was scanned
                   5029:        FirstName - first name from the sheet
                   5030:        LastName  - last name from the sheet
                   5031: 
                   5032:      if just_header was not true these key may also exist
                   5033: 
                   5034:        missingerror - a list of bubbled line numbers that had a blank bubble
                   5035:                       that is considered an error (if the operator had already
                   5036:                       okayed a blank bubble line as really being blank then
                   5037:                       that bubble line number won't appear here.
                   5038:        doubleerror  - a list of bubbled line numbers that had more than one
                   5039:                       bubble filled in and has not been corrected by the
                   5040:                       operator
                   5041:        maxquest     - the number of the last bubble line that was parsed
                   5042: 
                   5043:        (<number> starts at 1)
                   5044:        <number>.answer - zero or more letters representing the selected
                   5045:                          letters from the scanline for the bubble line 
                   5046:                          <number>.
                   5047:                          if blank there was either no bubble or there where
                   5048:                          multiple bubbles, (consult the keys missingerror and
                   5049:                          doubleerror if this is an error condition)
                   5050: 
                   5051: =cut
                   5052: 
1.82      albertel 5053: sub scantron_parse_scanline {
1.423     albertel 5054:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.82      albertel 5055:     my %record;
1.422     foxr     5056:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5057:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5058:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5059: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5060: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5061: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5062: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5063: 	    $record{'scantron.CODE'}=substr($data,
                   5064: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5065: 					    $$scantron_config{'CODElength'});
1.191     albertel 5066: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5067: 		$record{'scantron.useCODE'}=1;
                   5068: 	    }
1.192     albertel 5069: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5070: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5071: 	    }
1.82      albertel 5072: 	} else {
                   5073: 	    #FIXME interpret first N questions
                   5074: 	}
                   5075:     }
1.83      albertel 5076:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5077: 				  $$scantron_config{'IDlength'});
1.157     albertel 5078:     $record{'scantron.PaperID'}=
                   5079: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5080: 	       $$scantron_config{'PaperIDlength'});
                   5081:     $record{'scantron.FirstName'}=
                   5082: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5083: 	       $$scantron_config{'FirstNamelength'});
                   5084:     $record{'scantron.LastName'}=
                   5085: 	substr($data,$$scantron_config{'LastName'}-1,
                   5086: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5087:     if ($just_header) { return \%record; }
1.194     albertel 5088: 
1.82      albertel 5089:     my @alphabet=('A'..'Z');
                   5090:     my $questnum=0;
                   5091:     while ($questions) {
                   5092: 	$questnum++;
                   5093: 	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
                   5094: 	substr($questions,0,$$scantron_config{'Qlength'})='';
1.83      albertel 5095: 	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
1.239     albertel 5096: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.371     albertel 5097: 	    if ($currentquest eq '?'
                   5098: 		|| $currentquest eq '*') {
1.274     albertel 5099: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5100: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 5101: 	    } elsif (!defined($currentquest)
1.274     albertel 5102: 		     || $currentquest eq $$scantron_config{'Qoff'}
                   5103: 		     || $currentquest !~ /^[A-Z]$/) {
1.239     albertel 5104: 		$record{"scantron.$questnum.answer"}='';
                   5105: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5106: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5107: 		}
                   5108: 	    } else {
                   5109: 		$record{"scantron.$questnum.answer"}=$currentquest;
                   5110: 	    }
                   5111: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.371     albertel 5112: 	    if ($currentquest eq '?'
                   5113: 		|| $currentquest eq '*') {
1.274     albertel 5114: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5115: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 5116: 	    } elsif (!defined($currentquest)
                   5117: 		     || $currentquest eq $$scantron_config{'Qoff'} 
                   5118: 		     || $currentquest !~ /^\d$/) {
1.239     albertel 5119: 		$record{"scantron.$questnum.answer"}='';
                   5120: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5121: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5122: 		}
                   5123: 	    } else {
1.371     albertel 5124: 		# wrap zero back to J
                   5125: 		if ($currentquest eq '0') {
                   5126: 		    $record{"scantron.$questnum.answer"}=
                   5127: 			$alphabet[9];
                   5128: 		} else {
                   5129: 		    $record{"scantron.$questnum.answer"}=
                   5130: 			$alphabet[$currentquest-1];
                   5131: 		}
1.239     albertel 5132: 	    }
1.82      albertel 5133: 	} else {
1.239     albertel 5134: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
                   5135: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}) {
                   5136: 		$record{"scantron.$questnum.answer"}='';
                   5137: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5138: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5139: 		}
                   5140: 	    } else {
                   5141: 		$record{"scantron.$questnum.answer"}=
                   5142: 		    $alphabet[length($array[0])];
                   5143: 	    }
                   5144: 	    if (scalar(@array) gt 2) {
                   5145: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5146: 		my @ans=@array;
                   5147: 		my $i=length($ans[0]);shift(@ans);
                   5148: 		while ($#ans) {
                   5149: 		    $i+=length($ans[0])+1;
                   5150: 		    $record{"scantron.$questnum.answer"}.=$alphabet[$i];
                   5151: 		    shift(@ans);
                   5152: 		}
                   5153: 	    }
1.82      albertel 5154: 	}
                   5155:     }
1.83      albertel 5156:     $record{'scantron.maxquest'}=$questnum;
                   5157:     return \%record;
1.82      albertel 5158: }
                   5159: 
1.423     albertel 5160: =pod
                   5161: 
                   5162: =item scantron_add_delay
                   5163: 
                   5164:    Adds an error message that occurred during the grading phase to a
                   5165:    queue of messages to be shown after grading pass is complete
                   5166: 
                   5167:  Arguments:
1.424     albertel 5168:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5169:    $scanline    - the scanline that caused the error
                   5170:    $errormesage - the error message
                   5171:    $errorcode   - a numeric code for the error
                   5172: 
                   5173:  Side Effects:
1.424     albertel 5174:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5175: 
                   5176: =cut
                   5177: 
1.82      albertel 5178: sub scantron_add_delay {
1.140     albertel 5179:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5180:     push(@$delayqueue,
                   5181: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5182: 	  'ecode' => $errorcode }
                   5183: 	 );
1.82      albertel 5184: }
                   5185: 
1.423     albertel 5186: =pod
                   5187: 
                   5188: =item scantron_find_student
                   5189: 
1.424     albertel 5190:    Finds the username for the current scanline
                   5191: 
                   5192:   Arguments:
                   5193:    $scantron_record - hash result from scantron_parse_scanline
                   5194:    $scan_data       - hash of correction information 
                   5195:                       (see &scantron_getfile() form more information)
                   5196:    $idmap           - hash from &username_to_idmap()
                   5197:    $line            - number of current scanline
                   5198:  
                   5199:   Returns:
                   5200:    Either 'username:domain' or undef if unknown
                   5201: 
1.423     albertel 5202: =cut
                   5203: 
1.82      albertel 5204: sub scantron_find_student {
1.157     albertel 5205:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5206:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5207:     if ($scanID =~ /^\s*$/) {
                   5208:  	return &scan_data($scan_data,"$line.user");
                   5209:     }
1.83      albertel 5210:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5211:  	if (lc($id) eq lc($scanID)) {
                   5212:  	    return $$idmap{$id};
                   5213:  	}
1.83      albertel 5214:     }
                   5215:     return undef;
                   5216: }
                   5217: 
1.423     albertel 5218: =pod
                   5219: 
                   5220: =item scantron_filter
                   5221: 
1.424     albertel 5222:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5223:    hidden resources was selected
                   5224: 
1.423     albertel 5225: =cut
                   5226: 
1.83      albertel 5227: sub scantron_filter {
                   5228:     my ($curres)=@_;
1.331     albertel 5229: 
                   5230:     if (ref($curres) && $curres->is_problem()) {
                   5231: 	# if the user has asked to not have either hidden
                   5232: 	# or 'randomout' controlled resources to be graded
                   5233: 	# don't include them
                   5234: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5235: 	    && $curres->randomout) {
                   5236: 	    return 0;
                   5237: 	}
1.83      albertel 5238: 	return 1;
                   5239:     }
                   5240:     return 0;
1.82      albertel 5241: }
                   5242: 
1.423     albertel 5243: =pod
                   5244: 
                   5245: =item scantron_process_corrections
                   5246: 
1.424     albertel 5247:    Gets correction information out of submitted form data and corrects
                   5248:    the scanline
                   5249: 
1.423     albertel 5250: =cut
                   5251: 
1.157     albertel 5252: sub scantron_process_corrections {
                   5253:     my ($r) = @_;
1.257     albertel 5254:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5255:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5256:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5257:     my $which=$env{'form.scantron_line'};
1.200     albertel 5258:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5259:     my ($skip,$err,$errmsg);
1.257     albertel 5260:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5261: 	$skip=1;
1.257     albertel 5262:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5263: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5264: 	    $env{'form.scantron_domain'};
1.157     albertel 5265: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5266: 	($line,$err,$errmsg)=
                   5267: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5268: 				     'ID',{'newid'=>$newid,
1.257     albertel 5269: 				    'username'=>$env{'form.scantron_username'},
                   5270: 				    'domain'=>$env{'form.scantron_domain'}});
                   5271:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5272: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5273: 	my $newCODE;
1.192     albertel 5274: 	my %args;
1.190     albertel 5275: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5276: 	    $newCODE='use_unfound';
1.190     albertel 5277: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5278: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5279: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5280: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5281: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5282: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5283: 	}
1.257     albertel 5284: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5285: 	    $args{'CODE_ignore_dup'}=1;
                   5286: 	}
                   5287: 	$args{'CODE'}=$newCODE;
1.186     albertel 5288: 	($line,$err,$errmsg)=
                   5289: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5290: 				     'CODE',\%args);
1.257     albertel 5291:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5292: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5293: 	    ($line,$err,$errmsg)=
                   5294: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5295: 					 $which,'answer',
                   5296: 					 { 'question'=>$question,
1.257     albertel 5297: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5298: 	    if ($err) { last; }
                   5299: 	}
                   5300:     }
                   5301:     if ($err) {
1.398     albertel 5302: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5303:     } else {
1.200     albertel 5304: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5305: 	&scantron_putfile($scanlines,$scan_data);
                   5306:     }
                   5307: }
                   5308: 
1.423     albertel 5309: =pod
                   5310: 
                   5311: =item reset_skipping_status
                   5312: 
1.424     albertel 5313:    Forgets the current set of remember skipped scanlines (and thus
                   5314:    reverts back to considering all lines in the
                   5315:    scantron_skipped_<filename> file)
                   5316: 
1.423     albertel 5317: =cut
                   5318: 
1.200     albertel 5319: sub reset_skipping_status {
                   5320:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5321:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5322:     &scantron_putfile(undef,$scan_data);
                   5323: }
                   5324: 
1.423     albertel 5325: =pod
                   5326: 
                   5327: =item start_skipping
                   5328: 
1.424     albertel 5329:    Marks a scanline to be skipped. 
                   5330: 
1.423     albertel 5331: =cut
                   5332: 
1.376     albertel 5333: sub start_skipping {
1.200     albertel 5334:     my ($scan_data,$i)=@_;
                   5335:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5336:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5337: 	$remembered{$i}=2;
                   5338:     } else {
                   5339: 	$remembered{$i}=1;
                   5340:     }
1.200     albertel 5341:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5342: }
                   5343: 
1.423     albertel 5344: =pod
                   5345: 
                   5346: =item should_be_skipped
                   5347: 
1.424     albertel 5348:    Checks whether a scanline should be skipped.
                   5349: 
1.423     albertel 5350: =cut
                   5351: 
1.200     albertel 5352: sub should_be_skipped {
1.376     albertel 5353:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5354:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5355: 	# not redoing old skips
1.376     albertel 5356: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5357: 	return 0;
                   5358:     }
                   5359:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5360: 
                   5361:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5362: 	return 0;
                   5363:     }
1.200     albertel 5364:     return 1;
                   5365: }
                   5366: 
1.423     albertel 5367: =pod
                   5368: 
                   5369: =item remember_current_skipped
                   5370: 
1.424     albertel 5371:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5372:    file and remembers them into scan_data for later use.
                   5373: 
1.423     albertel 5374: =cut
                   5375: 
1.200     albertel 5376: sub remember_current_skipped {
                   5377:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5378:     my %to_remember;
                   5379:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5380: 	if ($scanlines->{'skipped'}[$i]) {
                   5381: 	    $to_remember{$i}=1;
                   5382: 	}
                   5383:     }
1.376     albertel 5384: 
1.200     albertel 5385:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5386:     &scantron_putfile(undef,$scan_data);
                   5387: }
                   5388: 
1.423     albertel 5389: =pod
                   5390: 
                   5391: =item check_for_error
                   5392: 
1.424     albertel 5393:     Checks if there was an error when attempting to remove a specific
                   5394:     scantron_.. bubble sheet data file. Prints out an error if
                   5395:     something went wrong.
                   5396: 
1.423     albertel 5397: =cut
                   5398: 
1.200     albertel 5399: sub check_for_error {
                   5400:     my ($r,$result)=@_;
                   5401:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5402: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5403:     }
                   5404: }
1.157     albertel 5405: 
1.423     albertel 5406: =pod
                   5407: 
                   5408: =item scantron_warning_screen
                   5409: 
1.424     albertel 5410:    Interstitial screen to make sure the operator has selected the
                   5411:    correct options before we start the validation phase.
                   5412: 
1.423     albertel 5413: =cut
                   5414: 
1.203     albertel 5415: sub scantron_warning_screen {
                   5416:     my ($button_text)=@_;
1.257     albertel 5417:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5418:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5419:     my $CODElist;
1.284     albertel 5420:     if ($scantron_config{'CODElocation'} &&
                   5421: 	$scantron_config{'CODEstart'} &&
                   5422: 	$scantron_config{'CODElength'}) {
                   5423: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5424: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5425: 	$CODElist=
                   5426: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5427: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5428:     }
1.203     albertel 5429:     return (<<STUFF);
                   5430: <p>
1.398     albertel 5431: <span class="LC_warning">Please double check the information
                   5432:                  below before clicking on '$button_text'</span>
1.203     albertel 5433: </p>
                   5434: <table>
1.284     albertel 5435: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5436: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5437: $CODElist
1.203     albertel 5438: </table>
                   5439: <br />
                   5440: <p> If this information is correct, please click on '$button_text'.</p>
                   5441: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5442: 
                   5443: <br />
                   5444: STUFF
                   5445: }
                   5446: 
1.423     albertel 5447: =pod
                   5448: 
                   5449: =item scantron_do_warning
                   5450: 
1.424     albertel 5451:    Check if the operator has picked something for all required
                   5452:    fields. Error out if something is missing.
                   5453: 
1.423     albertel 5454: =cut
                   5455: 
1.203     albertel 5456: sub scantron_do_warning {
                   5457:     my ($r)=@_;
1.324     albertel 5458:     my ($symb)=&get_symb($r);
1.203     albertel 5459:     if (!$symb) {return '';}
1.324     albertel 5460:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5461:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5462:     if ( $env{'form.selectpage'} eq '' ||
                   5463: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5464: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5465: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5466: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5467: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5468: 	} 
1.257     albertel 5469: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5470: 	    $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 5471: 	} 
1.257     albertel 5472: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5473: 	    $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 5474: 	} 
                   5475:     } else {
1.265     www      5476: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5477: 	$r->print(<<STUFF);
1.203     albertel 5478: $warning
1.265     www      5479: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5480: <input type="hidden" name="command" value="scantron_validate" />
                   5481: STUFF
1.237     albertel 5482:     }
1.352     albertel 5483:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5484:     return '';
                   5485: }
                   5486: 
1.423     albertel 5487: =pod
                   5488: 
                   5489: =item scantron_form_start
                   5490: 
1.424     albertel 5491:     html hidden input for remembering all selected grading options
                   5492: 
1.423     albertel 5493: =cut
                   5494: 
1.203     albertel 5495: sub scantron_form_start {
                   5496:     my ($max_bubble)=@_;
                   5497:     my $result= <<SCANTRONFORM;
                   5498: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5499:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5500:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5501:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5502:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5503:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5504:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5505:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5506:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5507:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5508: SCANTRONFORM
                   5509:     return $result;
                   5510: }
                   5511: 
1.423     albertel 5512: =pod
                   5513: 
                   5514: =item scantron_validate_file
                   5515: 
1.424     albertel 5516:     Dispatch routine for doing validation of a bubble sheet data file.
                   5517: 
                   5518:     Also processes any necessary information resets that need to
                   5519:     occur before validation begins (ignore previous corrections,
                   5520:     restarting the skipped records processing)
                   5521: 
1.423     albertel 5522: =cut
                   5523: 
1.157     albertel 5524: sub scantron_validate_file {
                   5525:     my ($r) = @_;
1.324     albertel 5526:     my ($symb)=&get_symb($r);
1.157     albertel 5527:     if (!$symb) {return '';}
1.324     albertel 5528:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5529:     
                   5530:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5531:     # them when doing the corrections reset
1.257     albertel 5532:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5533: 	&reset_skipping_status();
                   5534:     }
1.257     albertel 5535:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5536: 	&remember_current_skipped();
1.257     albertel 5537: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5538:     }
                   5539: 
1.257     albertel 5540:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5541: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5542: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5543: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5544: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5545:     }
1.200     albertel 5546: 
1.257     albertel 5547:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5548: 	&scantron_process_corrections($r);
                   5549:     }
1.424     albertel 5550:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5551:     #get the student pick code ready
                   5552:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5553:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5554:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5555:     $r->print($result);
                   5556:     
1.334     albertel 5557:     my @validate_phases=( 'sequence',
                   5558: 			  'ID',
1.157     albertel 5559: 			  'CODE',
                   5560: 			  'doublebubble',
                   5561: 			  'missingbubbles');
1.257     albertel 5562:     if (!$env{'form.validatepass'}) {
                   5563: 	$env{'form.validatepass'} = 0;
1.157     albertel 5564:     }
1.257     albertel 5565:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5566: 
                   5567:     my $stop=0;
                   5568:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5569: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5570: 	$r->rflush();
                   5571: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5572: 	{
                   5573: 	    no strict 'refs';
                   5574: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5575: 	}
                   5576:     }
                   5577:     if (!$stop) {
1.203     albertel 5578: 	my $warning=&scantron_warning_screen('Start Grading');
                   5579: 	$r->print(<<STUFF);
                   5580: Validation process complete.<br />
                   5581: $warning
                   5582: <input type="submit" name="submit" value="Start Grading" />
                   5583: <input type="hidden" name="command" value="scantron_process" />
                   5584: STUFF
                   5585: 
1.157     albertel 5586:     } else {
                   5587: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5588: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5589:     }
                   5590:     if ($stop) {
1.334     albertel 5591: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5592: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5593: 	    $r->print(' this error <br />');
                   5594: 
                   5595: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5596: 	} else {
                   5597: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5598: 	    $r->print(' using corrected info <br />');
                   5599: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5600: 	    $r->print(" this scanline saving it for later.");
                   5601: 	}
1.157     albertel 5602:     }
1.352     albertel 5603:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5604:     return '';
                   5605: }
                   5606: 
1.423     albertel 5607: 
                   5608: =pod
                   5609: 
                   5610: =item scantron_remove_file
                   5611: 
1.424     albertel 5612:    Removes the requested bubble sheet data file, makes sure that
                   5613:    scantron_original_<filename> is never removed
                   5614: 
                   5615: 
1.423     albertel 5616: =cut
                   5617: 
1.200     albertel 5618: sub scantron_remove_file {
1.192     albertel 5619:     my ($which)=@_;
1.257     albertel 5620:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5621:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5622:     my $file='scantron_';
1.200     albertel 5623:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5624: 	$file.=$which.'_';
1.192     albertel 5625:     } else {
                   5626: 	return 'refused';
                   5627:     }
1.257     albertel 5628:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5629:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5630: }
                   5631: 
1.423     albertel 5632: 
                   5633: =pod
                   5634: 
                   5635: =item scantron_remove_scan_data
                   5636: 
1.424     albertel 5637:    Removes all scan_data correction for the requested bubble sheet
                   5638:    data file.  (In the case that both the are doing skipped records we need
                   5639:    to remember the old skipped lines for the time being so that element
                   5640:    persists for a while.)
                   5641: 
1.423     albertel 5642: =cut
                   5643: 
1.200     albertel 5644: sub scantron_remove_scan_data {
1.257     albertel 5645:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5646:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5647:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5648:     my @todelete;
1.257     albertel 5649:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5650:     foreach my $key (@keys) {
                   5651: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5652: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5653: 		$key=~/remember_skipping/) {
                   5654: 		next;
                   5655: 	    }
1.192     albertel 5656: 	    push(@todelete,$key);
                   5657: 	}
                   5658:     }
1.200     albertel 5659:     my $result;
1.192     albertel 5660:     if (@todelete) {
1.200     albertel 5661: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5662:     }
                   5663:     return $result;
                   5664: }
                   5665: 
1.423     albertel 5666: 
                   5667: =pod
                   5668: 
                   5669: =item scantron_getfile
                   5670: 
1.424     albertel 5671:     Fetches the requested bubble sheet data file (all 3 versions), and
                   5672:     the scan_data hash
                   5673:   
                   5674:   Arguments:
                   5675:     None
                   5676: 
                   5677:   Returns:
                   5678:     2 hash references
                   5679: 
                   5680:      - first one has 
                   5681:          orig      -
                   5682:          corrected -
                   5683:          skipped   -  each of which points to an array ref of the specified
                   5684:                       file broken up into individual lines
                   5685:          count     - number of scanlines
                   5686:  
                   5687:      - second is the scan_data hash possible keys are
1.425     albertel 5688:        ($number refers to scanline numbered $number and thus the key affects
                   5689:         only that scanline
                   5690:         $bubline refers to the specific bubble line element and the aspects
                   5691:         refers to that specific bubble line element)
                   5692: 
                   5693:        $number.user - username:domain to use
                   5694:        $number.CODE_ignore_dup 
                   5695:                     - ignore the duplicate CODE error 
                   5696:        $number.useCODE
                   5697:                     - use the CODE in the scanline as is
                   5698:        $number.no_bubble.$bubline
                   5699:                     - it is valid that there is no bubbled in bubble
                   5700:                       at $number $bubline
                   5701:        remember_skipping
                   5702:                     - a frozen hash containing keys of $number and values
                   5703:                       of either 
                   5704:                         1 - we are on a 'do skipped records pass' and plan
                   5705:                             on processing this line
                   5706:                         2 - we are on a 'do skipped records pass' and this
                   5707:                             scanline has been marked to skip yet again
1.424     albertel 5708: 
1.423     albertel 5709: =cut
                   5710: 
1.157     albertel 5711: sub scantron_getfile {
1.200     albertel 5712:     #FIXME really would prefer a scantron directory
1.257     albertel 5713:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5714:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5715:     my $lines;
                   5716:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5717: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5718:     my %scanlines;
                   5719:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5720:     my $temp=$scanlines{'orig'};
                   5721:     $scanlines{'count'}=$#$temp;
                   5722: 
                   5723:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5724: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5725:     if ($lines eq '-1') {
                   5726: 	$scanlines{'corrected'}=[];
                   5727:     } else {
                   5728: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5729:     }
                   5730:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5731: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5732:     if ($lines eq '-1') {
                   5733: 	$scanlines{'skipped'}=[];
                   5734:     } else {
                   5735: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5736:     }
1.175     albertel 5737:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5738:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5739:     my %scan_data = @tmp;
                   5740:     return (\%scanlines,\%scan_data);
                   5741: }
                   5742: 
1.423     albertel 5743: =pod
                   5744: 
                   5745: =item lonnet_putfile
                   5746: 
1.424     albertel 5747:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   5748: 
                   5749:  Arguments:
                   5750:    $contents - data to store
                   5751:    $filename - filename to store $contents into
                   5752: 
                   5753:  Returns:
                   5754:    result value from &Apache::lonnet::finishuserfileupload
                   5755: 
1.423     albertel 5756: =cut
                   5757: 
1.157     albertel 5758: sub lonnet_putfile {
                   5759:     my ($contents,$filename)=@_;
1.257     albertel 5760:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5761:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5762:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 5763:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 5764: 
                   5765: }
                   5766: 
1.423     albertel 5767: =pod
                   5768: 
                   5769: =item scantron_putfile
                   5770: 
1.424     albertel 5771:     Stores the current version of the bubble sheet data files, and the
                   5772:     scan_data hash. (Does not modify the original version only the
                   5773:     corrected and skipped versions.
                   5774: 
                   5775:  Arguments:
                   5776:     $scanlines - hash ref that looks like the first return value from
                   5777:                  &scantron_getfile()
                   5778:     $scan_data - hash ref that looks like the second return value from
                   5779:                  &scantron_getfile()
                   5780: 
1.423     albertel 5781: =cut
                   5782: 
1.157     albertel 5783: sub scantron_putfile {
                   5784:     my ($scanlines,$scan_data) = @_;
1.200     albertel 5785:     #FIXME really would prefer a scantron directory
1.257     albertel 5786:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5787:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 5788:     if ($scanlines) {
                   5789: 	my $prefix='scantron_';
1.157     albertel 5790: # no need to update orig, shouldn't change
                   5791: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 5792: #		    $env{'form.scantron_selectfile'});
1.200     albertel 5793: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   5794: 			$prefix.'corrected_'.
1.257     albertel 5795: 			$env{'form.scantron_selectfile'});
1.200     albertel 5796: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   5797: 			$prefix.'skipped_'.
1.257     albertel 5798: 			$env{'form.scantron_selectfile'});
1.200     albertel 5799:     }
1.175     albertel 5800:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 5801: }
                   5802: 
1.423     albertel 5803: =pod
                   5804: 
                   5805: =item scantron_get_line
                   5806: 
1.424     albertel 5807:    Returns the correct version of the scanline
                   5808: 
                   5809:  Arguments:
                   5810:     $scanlines - hash ref that looks like the first return value from
                   5811:                  &scantron_getfile()
                   5812:     $scan_data - hash ref that looks like the second return value from
                   5813:                  &scantron_getfile()
                   5814:     $i         - number of the requested line (starts at 0)
                   5815: 
                   5816:  Returns:
                   5817:    A scanline, (either the original or the corrected one if it
                   5818:    exists), or undef if the requested scanline should be
                   5819:    skipped. (Either because it's an skipped scanline, or it's an
                   5820:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   5821:    pass.
                   5822: 
1.423     albertel 5823: =cut
                   5824: 
1.157     albertel 5825: sub scantron_get_line {
1.200     albertel 5826:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 5827:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   5828:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 5829:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   5830:     return $scanlines->{'orig'}[$i]; 
                   5831: }
                   5832: 
1.423     albertel 5833: =pod
                   5834: 
                   5835: =item scantron_todo_count
                   5836: 
1.424     albertel 5837:     Counts the number of scanlines that need processing.
                   5838: 
                   5839:  Arguments:
                   5840:     $scanlines - hash ref that looks like the first return value from
                   5841:                  &scantron_getfile()
                   5842:     $scan_data - hash ref that looks like the second return value from
                   5843:                  &scantron_getfile()
                   5844: 
                   5845:  Returns:
                   5846:     $count - number of scanlines to process
                   5847: 
1.423     albertel 5848: =cut
                   5849: 
1.200     albertel 5850: sub get_todo_count {
                   5851:     my ($scanlines,$scan_data)=@_;
                   5852:     my $count=0;
                   5853:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5854: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   5855: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5856: 	$count++;
                   5857:     }
                   5858:     return $count;
                   5859: }
                   5860: 
1.423     albertel 5861: =pod
                   5862: 
                   5863: =item scantron_put_line
                   5864: 
1.424     albertel 5865:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   5866:     data file.
                   5867: 
                   5868:  Arguments:
                   5869:     $scanlines - hash ref that looks like the first return value from
                   5870:                  &scantron_getfile()
                   5871:     $scan_data - hash ref that looks like the second return value from
                   5872:                  &scantron_getfile()
                   5873:     $i         - line number to update
                   5874:     $newline   - contents of the updated scanline
                   5875:     $skip      - if true make the line for skipping and update the
                   5876:                  'skipped' file
                   5877: 
1.423     albertel 5878: =cut
                   5879: 
1.157     albertel 5880: sub scantron_put_line {
1.200     albertel 5881:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 5882:     if ($skip) {
                   5883: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 5884: 	&start_skipping($scan_data,$i);
1.157     albertel 5885: 	return;
                   5886:     }
                   5887:     $scanlines->{'corrected'}[$i]=$newline;
                   5888: }
                   5889: 
1.423     albertel 5890: =pod
                   5891: 
                   5892: =item scantron_clear_skip
                   5893: 
1.424     albertel 5894:    Remove a line from the 'skipped' file
                   5895: 
                   5896:  Arguments:
                   5897:     $scanlines - hash ref that looks like the first return value from
                   5898:                  &scantron_getfile()
                   5899:     $scan_data - hash ref that looks like the second return value from
                   5900:                  &scantron_getfile()
                   5901:     $i         - line number to update
                   5902: 
1.423     albertel 5903: =cut
                   5904: 
1.376     albertel 5905: sub scantron_clear_skip {
                   5906:     my ($scanlines,$scan_data,$i)=@_;
                   5907:     if (exists($scanlines->{'skipped'}[$i])) {
                   5908: 	undef($scanlines->{'skipped'}[$i]);
                   5909: 	return 1;
                   5910:     }
                   5911:     return 0;
                   5912: }
                   5913: 
1.423     albertel 5914: =pod
                   5915: 
                   5916: =item scantron_filter_not_exam
                   5917: 
1.424     albertel 5918:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   5919:    filter out resources that are not marked as 'exam' mode
                   5920: 
1.423     albertel 5921: =cut
                   5922: 
1.334     albertel 5923: sub scantron_filter_not_exam {
                   5924:     my ($curres)=@_;
                   5925:     
                   5926:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   5927: 	# if the user has asked to not have either hidden
                   5928: 	# or 'randomout' controlled resources to be graded
                   5929: 	# don't include them
                   5930: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5931: 	    && $curres->randomout) {
                   5932: 	    return 0;
                   5933: 	}
                   5934: 	return 1;
                   5935:     }
                   5936:     return 0;
                   5937: }
                   5938: 
1.423     albertel 5939: =pod
                   5940: 
                   5941: =item scantron_validate_sequence
                   5942: 
1.424     albertel 5943:     Validates the selected sequence, checking for resource that are
                   5944:     not set to exam mode.
                   5945: 
1.423     albertel 5946: =cut
                   5947: 
1.334     albertel 5948: sub scantron_validate_sequence {
                   5949:     my ($r,$currentphase) = @_;
                   5950: 
                   5951:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5952:     my (undef,undef,$sequence)=
                   5953: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   5954: 
                   5955:     my $map=$navmap->getResourceByUrl($sequence);
                   5956: 
                   5957:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   5958:                                     value="ignore" />');
                   5959:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   5960: 	my @resources=
                   5961: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   5962: 	if (@resources) {
1.357     banghart 5963: 	    $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 5964: 	    return (1,$currentphase);
                   5965: 	}
                   5966:     }
                   5967: 
                   5968:     return (0,$currentphase+1);
                   5969: }
                   5970: 
1.423     albertel 5971: =pod
                   5972: 
                   5973: =item scantron_validate_ID
                   5974: 
1.424     albertel 5975:    Validates all scanlines in the selected file to not have any
                   5976:    invalid or underspecified student IDs
                   5977: 
1.423     albertel 5978: =cut
                   5979: 
1.157     albertel 5980: sub scantron_validate_ID {
                   5981:     my ($r,$currentphase) = @_;
                   5982:     
                   5983:     #get student info
                   5984:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5985:     my %idmap=&username_to_idmap($classlist);
                   5986: 
                   5987:     #get scantron line setup
1.257     albertel 5988:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5989:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5990: 
                   5991:     my %found=('ids'=>{},'usernames'=>{});
                   5992:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5993: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5994: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5995: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5996: 						 $scan_data);
                   5997: 	my $id=$$scan_record{'scantron.ID'};
                   5998: 	my $found;
                   5999: 	foreach my $checkid (keys(%idmap)) {
                   6000: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6001: 	}
                   6002: 	if ($found) {
                   6003: 	    my $username=$idmap{$found};
                   6004: 	    if ($found{'ids'}{$found}) {
                   6005: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6006: 					 $line,'duplicateID',$found);
1.194     albertel 6007: 		return(1,$currentphase);
1.157     albertel 6008: 	    } elsif ($found{'usernames'}{$username}) {
                   6009: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6010: 					 $line,'duplicateID',$username);
1.194     albertel 6011: 		return(1,$currentphase);
1.157     albertel 6012: 	    }
1.186     albertel 6013: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6014: 	    $found{'ids'}{$found}++;
                   6015: 	    $found{'usernames'}{$username}++;
                   6016: 	} else {
                   6017: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6018: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6019: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6020: 		    &scantron_get_correction($r,$i,$scan_record,
                   6021: 					     \%scantron_config,
                   6022: 					     $line,'duplicateID',$username);
1.194     albertel 6023: 		    return(1,$currentphase);
1.157     albertel 6024: 		} elsif (!defined($username)) {
                   6025: 		    &scantron_get_correction($r,$i,$scan_record,
                   6026: 					     \%scantron_config,
                   6027: 					     $line,'incorrectID');
1.194     albertel 6028: 		    return(1,$currentphase);
1.157     albertel 6029: 		}
                   6030: 		$found{'usernames'}{$username}++;
                   6031: 	    } else {
                   6032: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6033: 					 $line,'incorrectID');
1.194     albertel 6034: 		return(1,$currentphase);
1.157     albertel 6035: 	    }
                   6036: 	}
                   6037:     }
                   6038: 
                   6039:     return (0,$currentphase+1);
                   6040: }
                   6041: 
1.423     albertel 6042: =pod
                   6043: 
                   6044: =item scantron_get_correction
                   6045: 
1.424     albertel 6046:    Builds the interface screen to interact with the operator to fix a
                   6047:    specific error condition in a specific scanline
                   6048: 
                   6049:  Arguments:
                   6050:     $r           - Apache request object
                   6051:     $i           - number of the current scanline
                   6052:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6053:     $scan_config - hash ref as returned from &get_scantron_config()
                   6054:     $line        - full contents of the current scanline
                   6055:     $error       - error condition, valid values are
                   6056:                    'incorrectCODE', 'duplicateCODE',
                   6057:                    'doublebubble', 'missingbubble',
                   6058:                    'duplicateID', 'incorrectID'
                   6059:     $arg         - extra information needed
                   6060:        For errors:
                   6061:          - duplicateID   - paper number that this studentID was seen before on
                   6062:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6063:                            seen on before
                   6064:          - incorrectCODE - current incorrect CODE 
                   6065:          - doublebubble  - array ref of the bubble lines that have double
                   6066:                            bubble errors
                   6067:          - missingbubble - array ref of the bubble lines that have missing
                   6068:                            bubble errors
                   6069: 
1.423     albertel 6070: =cut
                   6071: 
1.157     albertel 6072: sub scantron_get_correction {
                   6073:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6074: 
                   6075: #FIXME in the case of a duplicated ID the previous line, probaly need
                   6076: #to show both the current line and the previous one and allow skipping
                   6077: #the previous one or the current one
                   6078: 
1.161     albertel 6079:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6080:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6081: 	$r->print(" for PaperID <tt>".
                   6082: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6083:     } else {
                   6084: 	$r->print(" in scanline $i <pre>".
                   6085: 		  $line."</pre> \n");
                   6086:     }
1.242     albertel 6087:     my $message="<p>The ID on the form is  <tt>".
                   6088: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6089: 	"The name on the paper is ".
                   6090: 	$$scan_record{'scantron.LastName'}.",".
                   6091: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6092: 
1.157     albertel 6093:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6094:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6095:     if ($error =~ /ID$/) {
1.186     albertel 6096: 	if ($error eq 'incorrectID') {
1.157     albertel 6097: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6098: 	} elsif ($error eq 'duplicateID') {
                   6099: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6100: 	}
1.242     albertel 6101: 	$r->print($message);
1.157     albertel 6102: 	$r->print("<p>How should I handle this? <br /> \n");
                   6103: 	$r->print("\n<ul><li> ");
                   6104: 	#FIXME it would be nice if this sent back the user ID and
                   6105: 	#could do partial userID matches
                   6106: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6107: 				       'scantron_username','scantron_domain'));
                   6108: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6109: 	$r->print("\n@".
1.257     albertel 6110: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6111: 
                   6112: 	$r->print('</li>');
1.186     albertel 6113:     } elsif ($error =~ /CODE$/) {
                   6114: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6115: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6116: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6117: 	    $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 6118: 	}
1.224     albertel 6119: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6120: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6121: 	$r->print($message);
1.186     albertel 6122: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6123: 	$r->print("\n<br /> ");
1.194     albertel 6124: 	my $i=0;
1.273     albertel 6125: 	if ($error eq 'incorrectCODE' 
                   6126: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6127: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6128: 	    if ($closest > 0) {
                   6129: 		foreach my $testcode (@{$closest}) {
                   6130: 		    my $checked='';
1.401     albertel 6131: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6132: 		    $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' />");
                   6133: 		    $r->print("\n<br />");
                   6134: 		    $i++;
                   6135: 		}
1.194     albertel 6136: 	    }
                   6137: 	}
1.273     albertel 6138: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6139: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6140: 	    $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>");
                   6141: 	    $r->print("\n<br />");
                   6142: 	}
1.194     albertel 6143: 
1.188     albertel 6144: 	$r->print(<<ENDSCRIPT);
                   6145: <script type="text/javascript">
                   6146: function change_radio(field) {
1.190     albertel 6147:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6148:     var i;
                   6149:     for (i=0;i<slct.length;i++) {
                   6150:         if (slct[i].value==field) { slct[i].checked=true; }
                   6151:     }
                   6152: }
                   6153: </script>
                   6154: ENDSCRIPT
1.187     albertel 6155: 	my $href="/adm/pickcode?".
1.359     www      6156: 	   "form=".&escape("scantronupload").
                   6157: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6158: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6159: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6160: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6161: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6162: 	    $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')\" />");
                   6163: 	    $r->print("\n<br />");
                   6164: 	}
1.272     albertel 6165: 	$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 6166: 	$r->print("\n<br /><br />");
1.157     albertel 6167:     } elsif ($error eq 'doublebubble') {
                   6168: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6169: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6170: 		  join(',',@{$arg}).'" />');
1.242     albertel 6171: 	$r->print($message);
1.157     albertel 6172: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6173: 	foreach my $question (@{$arg}) {
                   6174: 	    my $selected=$$scan_record{"scantron.$question.answer"};
1.422     foxr     6175: 	    &scantron_bubble_selector($r,$scan_config,$question,
                   6176: 				      split('',$selected));
1.157     albertel 6177: 	}
                   6178:     } elsif ($error eq 'missingbubble') {
                   6179: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6180: 	$r->print($message);
1.157     albertel 6181: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6182: 	$r->print("Some questions have no scanned bubbles\n");
                   6183: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6184: 		  join(',',@{$arg}).'" />');
                   6185: 	foreach my $question (@{$arg}) {
                   6186: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   6187: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   6188: 	}
                   6189:     } else {
                   6190: 	$r->print("\n<ul>");
                   6191:     }
                   6192:     $r->print("\n</li></ul>");
                   6193: 
                   6194: }
1.423     albertel 6195: 
                   6196: =pod
                   6197: 
                   6198: =item scantron_bubble_selector
                   6199:   
                   6200:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6201:    possibly showing the existing the selected bubbles if known
1.423     albertel 6202: 
                   6203:  Arguments:
                   6204:     $r           - Apache request object
                   6205:     $scan_config - hash from &get_scantron_config()
                   6206:     $quest       - number of the bubble line to make a corrector for
                   6207:     $selected    - array of letters of previously selected bubbles
                   6208:     $lines       - if present, number of bubble lines to show
                   6209: 
                   6210: =cut
                   6211: 
1.157     albertel 6212: sub scantron_bubble_selector {
1.422     foxr     6213:     my ($r,$scan_config,$quest,@selected, $lines)=@_;
1.157     albertel 6214:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6215: 
                   6216:     my $scmode=$$scan_config{'Qon'};
                   6217:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6218: 
1.422     foxr     6219: 
                   6220:     if (!defined($lines)) {
                   6221: 	$lines = 1;
                   6222:     }
                   6223:     my $total_lines = $lines*2;
1.157     albertel 6224:     my @alphabet=('A'..'Z');
1.422     foxr     6225:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6226: 
                   6227:     for (my $l = 0; $l < $lines; $l++) {
                   6228: 	if ($l != 0) {
                   6229: 	    $r->print('<tr>');
                   6230: 	}
                   6231: 
                   6232: 	# FIXME:  This loop probably has to be considerably more clever for
                   6233: 	#  multiline bubbles: User can multibubble by having bubbles in
                   6234: 	#  several lines.  User can skip lines legitimately etc. etc.
                   6235: 
                   6236: 	for (my $i=0;$i<$max;$i++) {
                   6237: 	    $r->print("\n".'<td align="center">');
                   6238: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6239: 		$r->print('X'); 
                   6240: 		shift(@selected) ;
                   6241: 	    } else { 
                   6242: 		$r->print('&nbsp;'); 
                   6243: 	    }
                   6244: 	    $r->print('</td>');
                   6245: 	    
                   6246: 	}
                   6247: 
                   6248: 	if ($l == 0) {
                   6249: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6250: 
                   6251: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6252: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6253: 	
                   6254: 	}
                   6255: 
                   6256: 	$r->print('</tr><tr>');
                   6257: 
                   6258: 	# FIXME: This may have to be a bit more clever for
                   6259: 	#        multiline questions (different values e.g..).
                   6260: 
                   6261: 	for (my $i=0;$i<$max;$i++) {
                   6262: 	    $r->print("\n".
                   6263: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6264: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6265: 	}
                   6266: 	$r->print('</tr>');
                   6267: 
                   6268: 	    
1.157     albertel 6269:     }
1.422     foxr     6270:     $r->print('</table>');
1.157     albertel 6271: }
                   6272: 
1.423     albertel 6273: =pod
                   6274: 
                   6275: =item num_matches
                   6276: 
1.424     albertel 6277:    Counts the number of characters that are the same between the two arguments.
                   6278: 
                   6279:  Arguments:
                   6280:    $orig - CODE from the scanline
                   6281:    $code - CODE to match against
                   6282: 
                   6283:  Returns:
                   6284:    $count - integer count of the number of same characters between the
                   6285:             two arguments
                   6286: 
1.423     albertel 6287: =cut
                   6288: 
1.194     albertel 6289: sub num_matches {
                   6290:     my ($orig,$code) = @_;
                   6291:     my @code=split(//,$code);
                   6292:     my @orig=split(//,$orig);
                   6293:     my $same=0;
                   6294:     for (my $i=0;$i<scalar(@code);$i++) {
                   6295: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6296:     }
                   6297:     return $same;
                   6298: }
                   6299: 
1.423     albertel 6300: =pod
                   6301: 
                   6302: =item scantron_get_closely_matching_CODEs
                   6303: 
1.424     albertel 6304:    Cycles through all CODEs and finds the set that has the greatest
                   6305:    number of same characters as the provided CODE
                   6306: 
                   6307:  Arguments:
                   6308:    $allcodes - hash ref returned by &get_codes()
                   6309:    $CODE     - CODE from the current scanline
                   6310: 
                   6311:  Returns:
                   6312:    2 element list
                   6313:     - first elements is number of how closely matching the best fit is 
                   6314:       (5 means best set has 5 matching characters)
                   6315:     - second element is an arrary ref containing the set of valid CODEs
                   6316:       that best fit the passed in CODE
                   6317: 
1.423     albertel 6318: =cut
                   6319: 
1.194     albertel 6320: sub scantron_get_closely_matching_CODEs {
                   6321:     my ($allcodes,$CODE)=@_;
                   6322:     my @CODEs;
                   6323:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6324: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6325:     }
                   6326: 
                   6327:     return ($#CODEs,$CODEs[-1]);
                   6328: }
                   6329: 
1.423     albertel 6330: =pod
                   6331: 
                   6332: =item get_codes
                   6333: 
1.424     albertel 6334:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6335:    set of remembered CODEs.
                   6336: 
                   6337:  Arguments:
                   6338:   $old_name - name of the set of remembered CODEs
                   6339:   $cdom     - domain of the course
                   6340:   $cnum     - internal course name
                   6341: 
                   6342:  Returns:
                   6343:   %allcodes - keys are the valid CODEs, values are all 1
                   6344: 
1.423     albertel 6345: =cut
                   6346: 
1.194     albertel 6347: sub get_codes {
1.280     foxr     6348:     my ($old_name, $cdom, $cnum) = @_;
                   6349:     if (!$old_name) {
                   6350: 	$old_name=$env{'form.scantron_CODElist'};
                   6351:     }
                   6352:     if (!$cdom) {
                   6353: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6354:     }
                   6355:     if (!$cnum) {
                   6356: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6357:     }
1.278     albertel 6358:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6359: 				    $cdom,$cnum);
                   6360:     my %allcodes;
                   6361:     if ($result{"type\0$old_name"} eq 'number') {
                   6362: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6363:     } else {
                   6364: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6365:     }
1.194     albertel 6366:     return %allcodes;
                   6367: }
                   6368: 
1.423     albertel 6369: =pod
                   6370: 
                   6371: =item scantron_validate_CODE
                   6372: 
1.424     albertel 6373:    Validates all scanlines in the selected file to not have any
                   6374:    invalid or underspecified CODEs and that none of the codes are
                   6375:    duplicated if this was requested.
                   6376: 
1.423     albertel 6377: =cut
                   6378: 
1.157     albertel 6379: sub scantron_validate_CODE {
                   6380:     my ($r,$currentphase) = @_;
1.257     albertel 6381:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6382:     if ($scantron_config{'CODElocation'} &&
                   6383: 	$scantron_config{'CODEstart'} &&
                   6384: 	$scantron_config{'CODElength'}) {
1.257     albertel 6385: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6386: 	    &FIXME_blow_up()
                   6387: 	}
                   6388:     } else {
                   6389: 	return (0,$currentphase+1);
                   6390:     }
                   6391:     
                   6392:     my %usedCODEs;
                   6393: 
1.194     albertel 6394:     my %allcodes=&get_codes();
1.186     albertel 6395: 
                   6396:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6397:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6398: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6399: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6400: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6401: 						 $scan_data);
                   6402: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6403: 	my $error=0;
1.224     albertel 6404: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6405: 	    &scantron_get_correction($r,$i,$scan_record,
                   6406: 				     \%scantron_config,
                   6407: 				     $line,'incorrectCODE',\%allcodes);
                   6408: 	    return(1,$currentphase);
                   6409: 	}
1.221     albertel 6410: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6411: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6412: 	    &scantron_get_correction($r,$i,$scan_record,
                   6413: 				     \%scantron_config,
1.194     albertel 6414: 				     $line,'incorrectCODE',\%allcodes);
                   6415: 	    return(1,$currentphase);
1.186     albertel 6416: 	}
1.214     albertel 6417: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6418: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6419: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6420: 	    &scantron_get_correction($r,$i,$scan_record,
                   6421: 				     \%scantron_config,
1.194     albertel 6422: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6423: 	    return(1,$currentphase);
1.186     albertel 6424: 	}
1.194     albertel 6425: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6426:     }
1.157     albertel 6427:     return (0,$currentphase+1);
                   6428: }
                   6429: 
1.423     albertel 6430: =pod
                   6431: 
                   6432: =item scantron_validate_doublebubble
                   6433: 
1.424     albertel 6434:    Validates all scanlines in the selected file to not have any
                   6435:    bubble lines with multiple bubbles marked.
                   6436: 
1.423     albertel 6437: =cut
                   6438: 
1.157     albertel 6439: sub scantron_validate_doublebubble {
                   6440:     my ($r,$currentphase) = @_;
                   6441:     #get student info
                   6442:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6443:     my %idmap=&username_to_idmap($classlist);
                   6444: 
                   6445:     #get scantron line setup
1.257     albertel 6446:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6447:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6448:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6449: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6450: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6451: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6452: 						 $scan_data);
                   6453: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6454: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6455: 				 'doublebubble',
                   6456: 				 $$scan_record{'scantron.doubleerror'});
                   6457:     	return (1,$currentphase);
                   6458:     }
                   6459:     return (0,$currentphase+1);
                   6460: }
                   6461: 
1.423     albertel 6462: =pod
                   6463: 
                   6464: =item scantron_get_maxbubble
                   6465: 
1.424     albertel 6466:    Returns the maximum number of bubble lines that are expected to
                   6467:    occur. Does this by walking the selected sequence rendering the
                   6468:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6469:    for what the current value of the problem counter is.
                   6470: 
                   6471:    Caches the result to $env{'form.scantron_maxbubble'}
                   6472: 
1.423     albertel 6473: =cut
                   6474: 
1.330     albertel 6475: sub scantron_get_maxbubble {    
1.257     albertel 6476:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6477: 	$env{'form.scantron_maxbubble'}) {
                   6478: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6479:     }
1.330     albertel 6480: 
1.191     albertel 6481:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6482:     my (undef,undef,$sequence)=
1.257     albertel 6483: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6484: 
1.191     albertel 6485:     my $map=$navmap->getResourceByUrl($sequence);
                   6486:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6487: 
                   6488:     &Apache::lonxml::clear_problem_counter();
                   6489: 
1.191     albertel 6490:     foreach my $resource (@resources) {
1.330     albertel 6491: 	my $result=&Apache::lonnet::ssi($resource->src(),
                   6492: 					('symb' => $resource->symb()));
1.191     albertel 6493:     }
                   6494:     &Apache::lonnet::delenv('scantron\.');
1.330     albertel 6495:     $env{'form.scantron_maxbubble'} =
                   6496: 	&Apache::lonxml::get_problem_counter()-1;
                   6497: 
1.257     albertel 6498:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6499: }
                   6500: 
1.423     albertel 6501: =pod
                   6502: 
                   6503: =item scantron_validate_missingbubbles
                   6504: 
1.424     albertel 6505:    Validates all scanlines in the selected file to not have any
                   6506:    bubble lines with missing bubbles that haven't been verified as missing.
                   6507: 
1.423     albertel 6508: =cut
                   6509: 
1.157     albertel 6510: sub scantron_validate_missingbubbles {
                   6511:     my ($r,$currentphase) = @_;
                   6512:     #get student info
                   6513:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6514:     my %idmap=&username_to_idmap($classlist);
                   6515: 
                   6516:     #get scantron line setup
1.257     albertel 6517:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6518:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6519:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6520:     if (!$max_bubble) { $max_bubble=2**31; }
                   6521:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6522: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6523: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6524: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6525: 						 $scan_data);
                   6526: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6527: 	my @to_correct;
                   6528: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6529: 	    if ($missing > $max_bubble) { next; }
                   6530: 	    push(@to_correct,$missing);
                   6531: 	}
                   6532: 	if (@to_correct) {
                   6533: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6534: 				     $line,'missingbubble',\@to_correct);
                   6535: 	    return (1,$currentphase);
                   6536: 	}
                   6537: 
                   6538:     }
                   6539:     return (0,$currentphase+1);
                   6540: }
                   6541: 
1.423     albertel 6542: =pod
                   6543: 
                   6544: =item scantron_process_students
                   6545: 
                   6546:    Routine that does the actual grading of the bubble sheet information.
                   6547: 
                   6548:    The parsed scanline hash is added to %env 
                   6549: 
                   6550:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6551:    foreach resource , with the form data of
                   6552: 
                   6553: 	'submitted'     =>'scantron' 
                   6554: 	'grade_target'  =>'grade',
                   6555: 	'grade_username'=> username of student
                   6556: 	'grade_domain'  => domain of student
                   6557: 	'grade_courseid'=> of course
                   6558: 	'grade_symb'    => symb of resource to grade
                   6559: 
                   6560:     This triggers a grading pass. The problem grading code takes care
                   6561:     of converting the bubbled letter information (now in %env) into a
                   6562:     valid submission.
                   6563: 
                   6564: =cut
                   6565: 
1.82      albertel 6566: sub scantron_process_students {
1.75      albertel 6567:     my ($r) = @_;
1.257     albertel 6568:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6569:     my ($symb)=&get_symb($r);
1.81      albertel 6570:     if (!$symb) {return '';}
1.324     albertel 6571:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6572: 
1.257     albertel 6573:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6574:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6575:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6576:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6577:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6578:     my $map=$navmap->getResourceByUrl($sequence);
                   6579:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6580: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6581:     my $result= <<SCANTRONFORM;
1.81      albertel 6582: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6583:   <input type="hidden" name="command" value="scantron_configphase" />
                   6584:   $default_form_data
                   6585: SCANTRONFORM
1.82      albertel 6586:     $r->print($result);
                   6587: 
                   6588:     my @delayqueue;
1.140     albertel 6589:     my %completedstudents;
                   6590:     
1.200     albertel 6591:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6592:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6593:  				    'Scantron Progress',$count,
1.195     albertel 6594: 				    'inline',undef,'scantronupload');
1.140     albertel 6595:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6596: 					  'Processing first student');
                   6597:     my $start=&Time::HiRes::time();
1.158     albertel 6598:     my $i=-1;
1.200     albertel 6599:     my ($uname,$udom,$started);
1.157     albertel 6600:     while ($i<$scanlines->{'count'}) {
                   6601:  	($uname,$udom)=('','');
                   6602:  	$i++;
1.200     albertel 6603:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6604:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 6605: 	if ($started) {
                   6606: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   6607: 						     'last student');
                   6608: 	}
                   6609: 	$started=1;
1.157     albertel 6610:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6611:  						 $scan_data);
                   6612:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   6613:  					      \%idmap,$i)) {
                   6614:   	    &scantron_add_delay(\@delayqueue,$line,
                   6615:  				'Unable to find a student that matches',1);
                   6616:  	    next;
                   6617:   	}
                   6618:  	if (exists $completedstudents{$uname}) {
                   6619:  	    &scantron_add_delay(\@delayqueue,$line,
                   6620:  				'Student '.$uname.' has multiple sheets',2);
                   6621:  	    next;
                   6622:  	}
                   6623:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 6624: 
                   6625: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 6626:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 6627: 
                   6628: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   6629: 	    &scantron_putfile($scanlines,$scan_data);
                   6630: 	}
1.161     albertel 6631: 	
                   6632: 	my $i=0;
1.83      albertel 6633: 	foreach my $resource (@resources) {
1.85      albertel 6634: 	    $i++;
1.193     albertel 6635: 	    my %form=('submitted'     =>'scantron',
                   6636: 		      'grade_target'  =>'grade',
                   6637: 		      'grade_username'=>$uname,
                   6638: 		      'grade_domain'  =>$udom,
1.257     albertel 6639: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 6640: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 6641: 	    if (exists($scan_record->{'scantron.CODE'})
                   6642: 		&& 
                   6643: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 6644: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 6645: 	    } else {
                   6646: 		$form{'CODE'}='';
1.193     albertel 6647: 	    }
                   6648: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 6649: 	    if ($result ne '') {
                   6650: 		&Apache::lonnet::logthis("scantron grading error -> $result");
1.257     albertel 6651: 		&Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
1.227     albertel 6652: 	    }
1.213     albertel 6653: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 6654: 	}
1.140     albertel 6655: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 6656: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 6657:     } continue {
1.330     albertel 6658: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 6659: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 6660:     }
1.140     albertel 6661:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 6662: #    my $lasttime = &Time::HiRes::time()-$start;
                   6663: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 6664: 
1.200     albertel 6665:     $r->print("</form>");
1.324     albertel 6666:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 6667:     return '';
1.75      albertel 6668: }
1.157     albertel 6669: 
1.423     albertel 6670: =pod
                   6671: 
                   6672: =item scantron_upload_scantron_data
                   6673: 
                   6674:     Creates the screen for adding a new bubble sheet data file to a course.
                   6675: 
                   6676: =cut
                   6677: 
1.157     albertel 6678: sub scantron_upload_scantron_data {
                   6679:     my ($r)=@_;
1.257     albertel 6680:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 6681:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 6682: 							  'domainid',
                   6683: 							  'coursename');
1.257     albertel 6684:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 6685: 						   'domainid');
1.324     albertel 6686:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 6687:     $r->print(<<UPLOAD);
                   6688: <script type="text/javascript" language="javascript">
                   6689:     function checkUpload(formname) {
                   6690: 	if (formname.upfile.value == "") {
                   6691: 	    alert("Please use the browse button to select a file from your local directory.");
                   6692: 	    return false;
                   6693: 	}
                   6694: 	formname.submit();
                   6695:     }
                   6696: </script>
                   6697: 
                   6698: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 6699: $default_form_data
1.181     albertel 6700: <table>
                   6701: <tr><td>$select_link </td></tr>
                   6702: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   6703: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   6704: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   6705: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   6706: </table>
1.157     albertel 6707: <input name='command' value='scantronupload_save' type='hidden' />
                   6708: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   6709: </form>
                   6710: UPLOAD
                   6711:     return '';
                   6712: }
                   6713: 
1.423     albertel 6714: =pod
                   6715: 
                   6716: =item scantron_upload_scantron_data_save
                   6717: 
                   6718:    Adds a provided bubble information data file to the course if user
                   6719:    has the correct privileges to do so.  
                   6720: 
                   6721: =cut
                   6722: 
1.157     albertel 6723: sub scantron_upload_scantron_data_save {
                   6724:     my($r)=@_;
1.324     albertel 6725:     my ($symb)=&get_symb($r,1);
1.182     albertel 6726:     my $doanotherupload=
                   6727: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   6728: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   6729: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   6730: 	'</form>'."\n";
1.257     albertel 6731:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 6732: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 6733: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 6734: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 6735: 	if ($symb) {
1.324     albertel 6736: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 6737: 	} else {
                   6738: 	    $r->print($doanotherupload);
                   6739: 	}
1.162     albertel 6740: 	return '';
                   6741:     }
1.257     albertel 6742:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       6743:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 6744:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 6745:     #FIXME
                   6746:     #copied from lonnet::userfileupload()
                   6747:     #make that function able to target a specified course
                   6748:     # Replace Windows backslashes by forward slashes
                   6749:     $fname=~s/\\/\//g;
                   6750:     # Get rid of everything but the actual filename
                   6751:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   6752:     # Replace spaces by underscores
                   6753:     $fname=~s/\s+/\_/g;
                   6754:     # Replace all other weird characters by nothing
                   6755:     $fname=~s/[^\w\.\-]//g;
                   6756:     # See if there is anything left
                   6757:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       6758:     my $uploadedfile=$fname;
1.157     albertel 6759:     $fname='scantron_orig_'.$fname;
1.257     albertel 6760:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 6761: 	$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 6762:     } else {
1.275     albertel 6763: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 6764: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 6765: 	    $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 6766: 	} else {
1.398     albertel 6767: 	    $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 6768: 	}
                   6769:     }
1.174     albertel 6770:     if ($symb) {
1.209     ng       6771: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 6772:     } else {
1.182     albertel 6773: 	$r->print($doanotherupload);
1.174     albertel 6774:     }
1.157     albertel 6775:     return '';
                   6776: }
                   6777: 
1.423     albertel 6778: =pod
                   6779: 
                   6780: =item valid_file
                   6781: 
1.424     albertel 6782:    Validates that the requested bubble data file exists in the course.
1.423     albertel 6783: 
                   6784: =cut
                   6785: 
1.202     albertel 6786: sub valid_file {
                   6787:     my ($requested_file)=@_;
                   6788:     foreach my $filename (sort(&scantron_filenames())) {
                   6789: 	if ($requested_file eq $filename) { return 1; }
                   6790:     }
                   6791:     return 0;
                   6792: }
                   6793: 
1.423     albertel 6794: =pod
                   6795: 
                   6796: =item scantron_download_scantron_data
                   6797: 
                   6798:    Shows a list of the three internal files (original, corrected,
                   6799:    skipped) for a specific bubble sheet data file that exists in the
                   6800:    course.
                   6801: 
                   6802: =cut
                   6803: 
1.202     albertel 6804: sub scantron_download_scantron_data {
                   6805:     my ($r)=@_;
1.324     albertel 6806:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 6807:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6808:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6809:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 6810:     if (! &valid_file($file)) {
                   6811: 	$r->print(<<ERROR);
                   6812: 	<p>
                   6813: 	    The requested file name was invalid.
                   6814:         </p>
                   6815: ERROR
1.324     albertel 6816: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 6817: 	return;
                   6818:     }
                   6819:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   6820:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   6821:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   6822:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   6823:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   6824:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   6825:     $r->print(<<DOWNLOAD);
                   6826:     <p>
                   6827: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   6828:     </p>
                   6829:     <p>
                   6830: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   6831:     </p>
                   6832:     <p>
                   6833: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   6834:     </p>
                   6835: DOWNLOAD
1.324     albertel 6836:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 6837:     return '';
                   6838: }
1.157     albertel 6839: 
1.423     albertel 6840: =pod
                   6841: 
                   6842: =back
                   6843: 
                   6844: =cut
                   6845: 
1.75      albertel 6846: #-------- end of section for handling grading scantron forms -------
                   6847: #
                   6848: #-------------------------------------------------------------------
                   6849: 
1.72      ng       6850: #-------------------------- Menu interface -------------------------
                   6851: #
                   6852: #--- Show a Grading Menu button - Calls the next routine ---
                   6853: sub show_grading_menu_form {
1.324     albertel 6854:     my ($symb)=@_;
1.125     ng       6855:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 6856: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 6857: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       6858: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   6859: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   6860: 	'</form>'."\n";
                   6861:     return $result;
                   6862: }
                   6863: 
1.77      ng       6864: # -- Retrieve choices for grading form
                   6865: sub savedState {
                   6866:     my %savedState = ();
1.257     albertel 6867:     if ($env{'form.saveState'}) {
                   6868: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       6869: 	    my ($key,$value) = split(/=/,$_,2);
                   6870: 	    $savedState{$key} = $value;
                   6871: 	}
                   6872:     }
                   6873:     return \%savedState;
                   6874: }
1.76      ng       6875: 
1.72      ng       6876: #--- Displays the main menu page -------
                   6877: sub gradingmenu {
                   6878:     my ($request) = @_;
1.324     albertel 6879:     my ($symb)=&get_symb($request);
1.72      ng       6880:     if (!$symb) {return '';}
1.76      ng       6881:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       6882: 
                   6883:     $request->print(<<GRADINGMENUJS);
                   6884: <script type="text/javascript" language="javascript">
1.116     ng       6885:     function checkChoice(formname,val,cmdx) {
                   6886: 	if (val <= 2) {
                   6887: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       6888: 	    var cmdsave = cmd;
1.116     ng       6889: 	} else {
                   6890: 	    cmd = cmdx;
1.118     ng       6891: 	    cmdsave = 'submission';
1.116     ng       6892: 	}
                   6893: 	formname.command.value = cmd;
1.118     ng       6894: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 6895: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       6896: 	if (val < 5) formname.submit();
                   6897: 	if (val == 5) {
1.72      ng       6898: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   6899: 	    formname.submit();
                   6900: 	}
1.238     albertel 6901: 	if (val < 7) formname.submit();
1.72      ng       6902:     }
                   6903: 
                   6904:     function checkReceiptNo(formname,nospace) {
                   6905: 	var receiptNo = formname.receipt.value;
                   6906: 	var checkOpt = false;
                   6907: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   6908: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   6909: 	if (checkOpt) {
                   6910: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   6911: 	    formname.receipt.value = "";
                   6912: 	    formname.receipt.focus();
                   6913: 	    return false;
                   6914: 	}
                   6915: 	return true;
                   6916:     }
                   6917: </script>
                   6918: GRADINGMENUJS
1.118     ng       6919:     &commonJSfunctions($request);
1.398     albertel 6920:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
1.324     albertel 6921:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       6922:     $result.=$table;
1.76      ng       6923:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       6924:     my $savedState = &savedState();
1.118     ng       6925:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       6926:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       6927:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       6928:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       6929: 
                   6930:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 6931: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       6932: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   6933: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       6934: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       6935: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       6936: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       6937: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   6938: 
1.326     albertel 6939:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   6940: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
1.72      ng       6941: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       6942: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   6943: 
1.326     albertel 6944:     $result.='<table width="100%" border="0">';
1.116     ng       6945:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.429     banghart 6946: 	'&nbsp;'.&mt('Select Section').': <select name="section" multiple="multiple" size="3">'."\n";
1.116     ng       6947:     if (ref($sections)) {
1.155     albertel 6948: 	foreach (sort (@$sections)) {
                   6949: 	    $result.='<option value="'.$_.'" '.
1.401     albertel 6950: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
1.155     albertel 6951: 	}
1.116     ng       6952:     }
1.401     albertel 6953:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.116     ng       6954: 
1.401     albertel 6955:     $result.=&mt('Student Status').':'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
1.72      ng       6956: 
1.116     ng       6957:     $result.='</td></tr>';
                   6958: 
1.288     albertel 6959:     $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
1.118     ng       6960: 	'<input type="radio" name="radioChoice" value="submission" '.
1.401     albertel 6961: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 6962: 	'</label> <select name="submitonly">'.
1.145     albertel 6963: 	'<option value="yes" '.
1.401     albertel 6964: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
1.301     albertel 6965: 	'<option value="queued" '.
1.401     albertel 6966: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
1.145     albertel 6967: 	'<option value="graded" '.
1.401     albertel 6968: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 6969: 	'<option value="incorrect" '.
1.401     albertel 6970: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 6971: 	'<option value="all" '.
1.401     albertel 6972: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       6973: 
1.116     ng       6974:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.288     albertel 6975: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.401     albertel 6976: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
1.288     albertel 6977: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       6978: 
1.118     ng       6979:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
1.288     albertel 6980: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.401     albertel 6981: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
1.288     albertel 6982: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       6983: 
1.116     ng       6984:     $result.='<tr bgcolor="#ffffe6"><td><br />'.
1.126     ng       6985: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       6986: 	'</td></tr></table>'."\n";
                   6987: 
                   6988:     $result.='</td><td valign="top">';
                   6989: 
1.326     albertel 6990:     $result.='<table width="100%" border="0">';
1.116     ng       6991:     $result.='<tr bgcolor="#ffffe6"><td>'.
1.184     www      6992: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   6993: 	' '.&mt('scores from file').' </td></tr>'."\n";
1.72      ng       6994: 
1.404     www      6995:     $result.='<tr bgcolor="#ffffe6"><td>'.
                   6996:         '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
                   6997:         ' '.&mt('clicker file').' </td></tr>'."\n";
1.400     www      6998: 
1.75      albertel 6999:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.116     ng       7000: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
1.184     www      7001: 	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
1.75      albertel 7002: 
1.257     albertel 7003:     if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
1.72      ng       7004: 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.184     www      7005: 	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   7006: 	    ' '.&mt('receipt').': '.
1.257     albertel 7007: 	    &Apache::lonnet::recprefix($env{'request.course.id'}).
1.326     albertel 7008: 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
1.72      ng       7009: 	    '</td></tr>'."\n";
                   7010:     } 
1.238     albertel 7011:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7012: 	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   7013: 	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
1.279     albertel 7014:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7015: 	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   7016: 	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
1.44      ng       7017: 
1.401     albertel 7018:     $result.='</table>'."\n".
1.72      ng       7019: 	'</td></tr></table>'."\n".
1.401     albertel 7020: 	'</td></tr></table></form>'."\n";
1.44      ng       7021:     return $result;
1.2       albertel 7022: }
                   7023: 
1.285     albertel 7024: sub reset_perm {
                   7025:     undef(%perm);
                   7026: }
                   7027: 
                   7028: sub init_perm {
                   7029:     &reset_perm();
1.300     albertel 7030:     foreach my $test_perm ('vgr','mgr','opa') {
                   7031: 
                   7032: 	my $scope = $env{'request.course.id'};
                   7033: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7034: 
                   7035: 	    $scope .= '/'.$env{'request.course.sec'};
                   7036: 	    if ( $perm{$test_perm}=
                   7037: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7038: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7039: 	    } else {
                   7040: 		delete($perm{$test_perm});
                   7041: 	    }
1.285     albertel 7042: 	}
                   7043:     }
                   7044: }
                   7045: 
1.400     www      7046: sub gather_clicker_ids {
1.408     albertel 7047:     my %clicker_ids;
1.400     www      7048: 
                   7049:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7050: 
                   7051:     # Set up a couple variables.
1.407     albertel 7052:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7053:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.400     www      7054: 
1.407     albertel 7055:     foreach my $student (keys(%$classlist)) {
1.400     www      7056: 
1.407     albertel 7057:         my $username = $classlist->{$student}->[$username_idx];
                   7058:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7059:         my $clickers =
1.408     albertel 7060: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7061:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7062:             $id=~s/^[\#0]+//;
1.421     www      7063:             $id=~s/[\-\:]//g;
1.407     albertel 7064:             if (exists($clicker_ids{$id})) {
1.408     albertel 7065: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7066:             } else {
1.408     albertel 7067: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7068:             }
                   7069:         }
                   7070:     }
1.407     albertel 7071:     return %clicker_ids;
1.400     www      7072: }
                   7073: 
1.402     www      7074: sub gather_adv_clicker_ids {
1.408     albertel 7075:     my %clicker_ids;
1.402     www      7076:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7077:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7078:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7079:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7080:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7081:             my ($puname,$pudom)=split(/\:/,$person);
                   7082:             my $clickers =
1.408     albertel 7083: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7084:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7085: 		$id=~s/^[\#0]+//;
1.421     www      7086:                 $id=~s/[\-\:]//g;
1.408     albertel 7087: 		if (exists($clicker_ids{$id})) {
                   7088: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7089: 		} else {
                   7090: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7091: 		}
1.405     www      7092:             }
1.402     www      7093:         }
                   7094:     }
1.407     albertel 7095:     return %clicker_ids;
1.402     www      7096: }
                   7097: 
1.413     www      7098: sub clicker_grading_parameters {
                   7099:     return ('gradingmechanism' => 'scalar',
                   7100:             'upfiletype' => 'scalar',
                   7101:             'specificid' => 'scalar',
                   7102:             'pcorrect' => 'scalar',
                   7103:             'pincorrect' => 'scalar');
                   7104: }
                   7105: 
1.400     www      7106: sub process_clicker {
                   7107:     my ($r)=@_;
                   7108:     my ($symb)=&get_symb($r);
                   7109:     if (!$symb) {return '';}
                   7110:     my $result=&checkforfile_js();
                   7111:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7112:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7113:     $result.=$table;
                   7114:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7115:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7116:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7117:         '.</b></td></tr>'."\n";
                   7118:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7119: # Attempt to restore parameters from last session, set defaults if not present
                   7120:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7121:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7122:                                                  \%Saveable_Parameters);
                   7123:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7124:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7125:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7126:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7127: 
                   7128:     my %checked;
                   7129:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7130:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7131:           $checked{$gradingmechanism}="checked='checked'";
                   7132:        }
                   7133:     }
                   7134: 
1.400     www      7135:     my $upload=&mt("Upload File");
                   7136:     my $type=&mt("Type");
1.402     www      7137:     my $attendance=&mt("Award points just for participation");
                   7138:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7139:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7140:     my $pcorrect=&mt("Percentage points for correct solution");
                   7141:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7142:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7143: 						   ('iclicker' => 'i>clicker',
                   7144:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7145:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7146:     $result.=<<ENDUPFORM;
1.402     www      7147: <script type="text/javascript">
                   7148: function sanitycheck() {
                   7149: // Accept only integer percentages
                   7150:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7151:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7152: // Find out grading choice
                   7153:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7154:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7155:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7156:       }
                   7157:    }
                   7158: // By default, new choice equals user selection
                   7159:    newgradingchoice=gradingchoice;
                   7160: // Not good to give more points for false answers than correct ones
                   7161:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7162:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7163:    }
                   7164: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7165:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7166:       document.forms.gradesupload.pcorrect.value=100;
                   7167:       document.forms.gradesupload.pincorrect.value=100;
                   7168:    }
                   7169: // If the values are different, cannot be attendance only
                   7170:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7171:        (gradingchoice=='attendance')) {
                   7172:        newgradingchoice='personnel';
                   7173:    }
                   7174: // Change grading choice to new one
                   7175:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7176:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7177:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7178:       } else {
                   7179:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7180:       }
                   7181:    }
                   7182: // Remember the old state
                   7183:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7184: }
                   7185: </script>
1.400     www      7186: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7187: <input type="hidden" name="symb" value="$symb" />
                   7188: <input type="hidden" name="command" value="processclickerfile" />
                   7189: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7190: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7191: <input type="file" name="upfile" size="50" />
                   7192: <br /><label>$type: $selectform</label>
1.413     www      7193: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
                   7194: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
                   7195: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
1.414     www      7196: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7197: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7198: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7199: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7200: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7201: </form>
                   7202: ENDUPFORM
                   7203:     $result.='</td></tr></table>'."\n".
                   7204:              '</td></tr></table><br /><br />'."\n";
                   7205:     $result.=&show_grading_menu_form($symb);
                   7206:     return $result;
                   7207: }
                   7208: 
                   7209: sub process_clicker_file {
                   7210:     my ($r)=@_;
                   7211:     my ($symb)=&get_symb($r);
                   7212:     if (!$symb) {return '';}
1.413     www      7213: 
                   7214:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7215:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7216:                                               \%Saveable_Parameters);
                   7217: 
1.400     www      7218:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7219:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7220: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7221: 	return $result.&show_grading_menu_form($symb);
1.404     www      7222:     }
1.407     albertel 7223:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7224:     my %correct_ids;
1.404     www      7225:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7226: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7227:     }
                   7228:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7229: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7230: 	   $correct_id=~tr/a-z/A-Z/;
                   7231: 	   $correct_id=~s/\s//gs;
                   7232: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7233:            $correct_id=~s/[\-\:]//g;
1.414     www      7234:            if ($correct_id) {
                   7235: 	      $correct_ids{$correct_id}='specified';
                   7236:            }
                   7237:         }
1.400     www      7238:     }
1.404     www      7239:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7240: 	$result.=&mt('Score based on attendance only');
1.404     www      7241:     } else {
1.408     albertel 7242: 	my $number=0;
1.411     www      7243: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7244: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7245: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7246: 	    if ($correct_ids{$id} eq 'specified') {
                   7247: 		$result.=&mt('specified');
                   7248: 	    } else {
                   7249: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7250: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7251: 	    }
                   7252: 	    $number++;
                   7253: 	}
1.411     www      7254:         $result.="</p>\n";
1.408     albertel 7255: 	if ($number==0) {
                   7256: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7257: 	    return $result.&show_grading_menu_form($symb);
                   7258: 	}
1.404     www      7259:     }
1.405     www      7260:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7261:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7262: 		     '<span class="LC_error">',
                   7263: 		     '</span>',
                   7264: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7265:         return $result.&show_grading_menu_form($symb);
                   7266:     }
1.410     www      7267: 
                   7268: # Were able to get all the info needed, now analyze the file
                   7269: 
1.411     www      7270:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7271:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7272:     my $heading=&mt('Scanning clicker file');
                   7273:     $result.=(<<ENDHEADER);
                   7274: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7275: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7276: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7277: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7278: <input type="hidden" name="symb" value="$symb" />
                   7279: <input type="hidden" name="command" value="assignclickergrades" />
                   7280: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7281: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7282: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7283: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7284: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7285: ENDHEADER
1.408     albertel 7286:     my %responses;
                   7287:     my @questiontitles;
1.405     www      7288:     my $errormsg='';
                   7289:     my $number=0;
                   7290:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7291: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7292:     }
1.419     www      7293:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7294:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7295:     }
1.411     www      7296:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7297:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   7298:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7299:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7300:              '<br />';
1.414     www      7301: # Remember Question Titles
                   7302: # FIXME: Possibly need delimiter other than ":"
                   7303:     for (my $i=0;$i<$number;$i++) {
                   7304:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7305:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7306:     }
1.411     www      7307:     my $correct_count=0;
                   7308:     my $student_count=0;
                   7309:     my $unknown_count=0;
1.414     www      7310: # Match answers with usernames
                   7311: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7312:     foreach my $id (keys(%responses)) {
1.410     www      7313:        if ($correct_ids{$id}) {
1.414     www      7314:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7315:           $correct_count++;
1.410     www      7316:        } elsif ($clicker_ids{$id}) {
                   7317:           $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7318:           $student_count++;
1.410     www      7319:        } else {
1.411     www      7320:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7321:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7322:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7323:                    "\n".&mt("Domain").": ".
                   7324:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7325:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7326:           $unknown_count++;
1.410     www      7327:        }
1.405     www      7328:     }
1.412     www      7329:     $result.='<hr />'.
                   7330:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7331:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7332:        if ($correct_count==0) {
                   7333:           $errormsg.="Found no correct answers answers for grading!";
                   7334:        } elsif ($correct_count>1) {
1.414     www      7335:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7336:        }
                   7337:     }
1.428     www      7338:     if ($number<1) {
                   7339:        $errormsg.="Found no questions.";
                   7340:     }
1.412     www      7341:     if ($errormsg) {
                   7342:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7343:     } else {
                   7344:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7345:     }
                   7346:     $result.='</form></td></tr></table>'."\n".
1.410     www      7347:              '</td></tr></table><br /><br />'."\n";
1.404     www      7348:     return $result.&show_grading_menu_form($symb);
1.400     www      7349: }
                   7350: 
1.405     www      7351: sub iclicker_eval {
1.406     www      7352:     my ($questiontitles,$responses)=@_;
1.405     www      7353:     my $number=0;
                   7354:     my $errormsg='';
                   7355:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7356:         my %components=&Apache::loncommon::record_sep($line);
                   7357:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7358: 	if ($entries[0] eq 'Question') {
                   7359: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7360: 		$$questiontitles[$number]=$entries[$i];
                   7361: 		$number++;
                   7362: 	    }
                   7363: 	}
                   7364: 	if ($entries[0]=~/^\#/) {
                   7365: 	    my $id=$entries[0];
                   7366: 	    my @idresponses;
                   7367: 	    $id=~s/^[\#0]+//;
                   7368: 	    for (my $i=0;$i<$number;$i++) {
                   7369: 		my $idx=3+$i*6;
                   7370: 		push(@idresponses,$entries[$idx]);
                   7371: 	    }
                   7372: 	    $$responses{$id}=join(',',@idresponses);
                   7373: 	}
1.405     www      7374:     }
                   7375:     return ($errormsg,$number);
                   7376: }
                   7377: 
1.419     www      7378: sub interwrite_eval {
                   7379:     my ($questiontitles,$responses)=@_;
                   7380:     my $number=0;
                   7381:     my $errormsg='';
1.420     www      7382:     my $skipline=1;
                   7383:     my $questionnumber=0;
                   7384:     my %idresponses=();
1.419     www      7385:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   7386:         my %components=&Apache::loncommon::record_sep($line);
                   7387:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      7388:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   7389:         if ($entries[1] eq 'Response') { $skipline=1; }
                   7390:         next if $skipline;
                   7391:         if ($entries[0]!=$questionnumber) {
                   7392:            $questionnumber=$entries[0];
                   7393:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   7394:            $number++;
1.419     www      7395:         }
1.420     www      7396:         my $id=$entries[4];
                   7397:         $id=~s/^[\#0]+//;
1.421     www      7398:         $id=~s/^v\d*\://i;
                   7399:         $id=~s/[\-\:]//g;
1.420     www      7400:         $idresponses{$id}[$number]=$entries[6];
                   7401:     }
                   7402:     foreach my $id (keys %idresponses) {
                   7403:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   7404:        $$responses{$id}=~s/^\s*\,//;
1.419     www      7405:     }
                   7406:     return ($errormsg,$number);
                   7407: }
                   7408: 
1.414     www      7409: sub assign_clicker_grades {
                   7410:     my ($r)=@_;
                   7411:     my ($symb)=&get_symb($r);
                   7412:     if (!$symb) {return '';}
1.416     www      7413: # See which part we are saving to
                   7414:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   7415: # FIXME: This should probably look for the first handgradeable part
                   7416:     my $part=$$partlist[0];
                   7417: # Start screen output
1.414     www      7418:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      7419: 
1.414     www      7420:     my $heading=&mt('Assigning grades based on clicker file');
                   7421:     $result.=(<<ENDHEADER);
                   7422: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7423: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7424: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7425: ENDHEADER
                   7426: # Get correct result
                   7427: # FIXME: Possibly need delimiter other than ":"
                   7428:     my @correct=();
1.415     www      7429:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   7430:     my $number=$env{'form.number'};
                   7431:     if ($gradingmechanism ne 'attendance') {
1.414     www      7432:        foreach my $key (keys(%env)) {
                   7433:           if ($key=~/^form\.correct\:/) {
                   7434:              my @input=split(/\,/,$env{$key});
                   7435:              for (my $i=0;$i<=$#input;$i++) {
                   7436:                  if (($correct[$i]) && ($input[$i]) &&
                   7437:                      ($correct[$i] ne $input[$i])) {
                   7438:                     $result.='<br /><span class="LC_warning">'.
                   7439:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   7440:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   7441:                  } elsif ($input[$i]) {
                   7442:                     $correct[$i]=$input[$i];
                   7443:                  }
                   7444:              }
                   7445:           }
                   7446:        }
1.415     www      7447:        for (my $i=0;$i<$number;$i++) {
1.414     www      7448:           if (!$correct[$i]) {
                   7449:              $result.='<br /><span class="LC_error">'.
                   7450:                       &mt('No correct result given for question "[_1]"!',
                   7451:                           $env{'form.question:'.$i}).'</span>';
                   7452:           }
                   7453:        }
                   7454:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   7455:     }
                   7456: # Start grading
1.415     www      7457:     my $pcorrect=$env{'form.pcorrect'};
                   7458:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      7459:     my $storecount=0;
1.415     www      7460:     foreach my $key (keys(%env)) {
1.420     www      7461:        my $user='';
1.415     www      7462:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      7463:           $user=$1;
                   7464:        }
                   7465:        if ($key=~/^form\.unknown\:(.*)$/) {
                   7466:           my $id=$1;
                   7467:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   7468:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
                   7469:           }
                   7470:        }
                   7471:        if ($user) { 
1.415     www      7472:           my @answer=split(/\,/,$env{$key});
                   7473:           my $sum=0;
                   7474:           for (my $i=0;$i<$number;$i++) {
                   7475:              if ($answer[$i]) {
                   7476:                 if ($gradingmechanism eq 'attendance') {
                   7477:                    $sum+=$pcorrect;
                   7478:                 } else {
                   7479:                    if ($answer[$i] eq $correct[$i]) {
                   7480:                       $sum+=$pcorrect;
                   7481:                    } else {
                   7482:                       $sum+=$pincorrect;
                   7483:                    }
                   7484:                 }
                   7485:              }
                   7486:           }
1.416     www      7487:           my $ave=$sum/(100*$number);
                   7488: # Store
                   7489:           my ($username,$domain)=split(/\:/,$user);
                   7490:           my %grades=();
                   7491:           $grades{"resource.$part.solved"}='correct_by_override';
                   7492:           $grades{"resource.$part.awarded"}=$ave;
                   7493:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   7494:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   7495:                                                  $env{'request.course.id'},
                   7496:                                                  $domain,$username);
                   7497:           if ($returncode ne 'ok') {
                   7498:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   7499:           } else {
                   7500:              $storecount++;
                   7501:           }
1.415     www      7502:        }
                   7503:     }
                   7504: # We are done
1.416     www      7505:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   7506:              '</td></tr></table>'."\n".
1.414     www      7507:              '</td></tr></table><br /><br />'."\n";
                   7508:     return $result.&show_grading_menu_form($symb);
                   7509: }
                   7510: 
1.1       albertel 7511: sub handler {
1.41      ng       7512:     my $request=$_[0];
1.102     albertel 7513: 
1.285     albertel 7514:     &reset_perm();
1.257     albertel 7515:     if ($env{'browser.mathml'}) {
1.141     www      7516: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       7517:     } else {
1.141     www      7518: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       7519:     }
                   7520:     $request->send_http_header;
1.44      ng       7521:     return '' if $request->header_only;
1.41      ng       7522:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 7523:     my $symb=&get_symb($request,1);
1.160     albertel 7524:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   7525:     my $command=$commands[0];
                   7526:     if ($#commands > 0) {
                   7527: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   7528:     }
1.353     albertel 7529:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 7530:     if ($symb eq '' && $command eq '') {
1.257     albertel 7531: 	if ($env{'user.adv'}) {
                   7532: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   7533: 		($env{'form.codethree'})) {
                   7534: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   7535: 		    $env{'form.codethree'};
1.41      ng       7536: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   7537: 		    &Apache::lonnet::checkin($token);
                   7538: 		if ($tsymb) {
1.137     albertel 7539: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       7540: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 7541: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   7542: 					  ('grade_username' => $tuname,
                   7543: 					   'grade_domain' => $tudom,
                   7544: 					   'grade_courseid' => $tcrsid,
                   7545: 					   'grade_symb' => $tsymb)));
1.41      ng       7546: 		    } else {
1.45      ng       7547: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 7548: 		    }
1.41      ng       7549: 		} else {
1.45      ng       7550: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       7551: 		}
1.14      www      7552: 	    } else {
1.41      ng       7553: 		$request->print(&Apache::lonxml::tokeninputfield());
                   7554: 	    }
                   7555: 	}
                   7556:     } else {
1.285     albertel 7557: 	&init_perm();
1.104     albertel 7558: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 7559: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 7560: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       7561: 	    &pickStudentPage($request);
1.103     albertel 7562: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       7563: 	    &displayPage($request);
1.104     albertel 7564: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       7565: 	    &updateGradeByPage($request);
1.104     albertel 7566: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       7567: 	    &processGroup($request);
1.104     albertel 7568: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.41      ng       7569: 	    $request->print(&gradingmenu($request));
1.104     albertel 7570: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       7571: 	    $request->print(&viewgrades($request));
1.104     albertel 7572: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       7573: 	    $request->print(&processHandGrade($request));
1.106     albertel 7574: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       7575: 	    $request->print(&editgrades($request));
1.106     albertel 7576: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       7577: 	    $request->print(&verifyreceipt($request));
1.400     www      7578:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   7579:             $request->print(&process_clicker($request));
                   7580:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   7581:             $request->print(&process_clicker_file($request));
1.414     www      7582:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   7583:             $request->print(&assign_clicker_grades($request));
1.106     albertel 7584: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       7585: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 7586: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       7587: 	    $request->print(&csvupload($request));
1.106     albertel 7588: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       7589: 	    $request->print(&csvuploadmap($request));
1.246     albertel 7590: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 7591: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 7592: 		$request->print(&csvuploadoptions($request));
1.41      ng       7593: 	    } else {
1.257     albertel 7594: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   7595: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       7596: 		} else {
1.257     albertel 7597: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       7598: 		}
                   7599: 		$request->print(&csvuploadmap($request));
                   7600: 	    }
1.246     albertel 7601: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   7602: 	    $request->print(&csvuploadassign($request));
1.106     albertel 7603: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 7604: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 7605:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   7606:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 7607: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   7608: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 7609: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 7610: 	    $request->print(&scantron_process_students($request));
1.157     albertel 7611:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 7612:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   7613: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 7614:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 7615:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 7616:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   7617: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 7618:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 7619:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 7620: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 7621:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 7622: 	} elsif ($command) {
1.157     albertel 7623: 	    $request->print("Access Denied ($command)");
1.26      albertel 7624: 	}
1.2       albertel 7625:     }
1.353     albertel 7626:     $request->print(&Apache::loncommon::end_page());
1.44      ng       7627:     return '';
                   7628: }
                   7629: 
1.1       albertel 7630: 1;
                   7631: 
1.13      albertel 7632: __END__;

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