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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.433   ! banghart    4: # $Id: grades.pm,v 1.432 2007/08/21 22:21:54 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.433   ! banghart 3098: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
        !          3099: 	$result='<span class="LC_warning">'.
        !          3100: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
        !          3101: 	        $section_display, $env{'form.Status'}).
        !          3102: 	    '</span>';
1.96      albertel 3103:     }
1.324     albertel 3104:     $result.=&show_grading_menu_form($symb);
1.41      ng       3105:     return $result;
                   3106: }
                   3107: 
1.44      ng       3108: #--- call by previous routine to display each student
1.41      ng       3109: sub viewstudentgrade {
1.324     albertel 3110:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3111:     my ($uname,$udom) = split(/:/,$student);
                   3112:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3113:     my %aggregates = (); 
1.233     albertel 3114:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3115: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3116: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3117: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3118: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3119: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3120:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3121:     foreach my $apart (@$parts) {
                   3122: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3123: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3124:         $result.='<td align="center">';
1.269     raeburn  3125:         my ($aggtries,$totaltries);
                   3126:         unless (exists($aggregates{$part})) {
1.270     albertel 3127: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3128: 
                   3129: 	    $aggtries = $totaltries;
1.269     raeburn  3130:             if ($$last_resets{$part}) {  
1.270     albertel 3131:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3132: 					   $part);
                   3133:             }
1.269     raeburn  3134:             $result.='<input type="hidden" name="'.
                   3135:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3136:             $result.='<input type="hidden" name="'.
                   3137:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3138:             $aggregates{$part} = 1;
                   3139:         }
1.41      ng       3140: 	if ($type eq 'awarded') {
1.320     albertel 3141: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3142: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3143: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3144: 	    $result.='<input type="text" name="'.
1.89      albertel 3145: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3146: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3147: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3148: 	} elsif ($type eq 'solved') {
                   3149: 	    my ($status,$foo)=split(/_/,$score,2);
                   3150: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3151: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3152: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3153: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3154: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3155: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3156: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3157: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3158: 	    $result.='<option>reset status</option>';
1.126     ng       3159: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3160: 	} else {
                   3161: 	    $result.='<input type="hidden" name="'.
                   3162: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3163: 		    "\n";
1.233     albertel 3164: 	    $result.='<input type="text" name="'.
1.122     ng       3165: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3166: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3167: 	}
                   3168:     }
                   3169:     $result.='</tr>';
                   3170:     return $result;
1.38      ng       3171: }
                   3172: 
1.44      ng       3173: #--- change scores for all the students in a section/class
                   3174: #    record does not get update if unchanged
1.38      ng       3175: sub editgrades {
1.41      ng       3176:     my ($request) = @_;
                   3177: 
1.324     albertel 3178:     my $symb=&get_symb($request);
1.433   ! banghart 3179:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
        !          3180:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
        !          3181:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
        !          3182:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3183: 
1.44      ng       3184:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3185:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3186: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3187: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3188: 
                   3189:     my %scoreptr = (
                   3190: 		    'correct'  =>'correct_by_override',
                   3191: 		    'incorrect'=>'incorrect_by_override',
                   3192: 		    'excused'  =>'excused',
                   3193: 		    'ungraded' =>'ungraded_attempted',
                   3194: 		    'nothing'  => '',
                   3195: 		    );
1.257     albertel 3196:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3197: 
1.44      ng       3198:     my (@partid);
                   3199:     my %weight = ();
1.54      albertel 3200:     my %columns = ();
1.44      ng       3201:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3202: 
1.324     albertel 3203:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3204:     my $header;
1.257     albertel 3205:     while ($ctr < $env{'form.totalparts'}) {
                   3206: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3207: 	push @partid,$partid;
1.257     albertel 3208: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3209: 	$ctr++;
1.54      albertel 3210:     }
1.324     albertel 3211:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3212:     foreach my $partid (@partid) {
                   3213: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3214: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3215: 	$columns{$partid}=2;
                   3216: 	foreach my $stores (@parts) {
                   3217: 	    my ($part,$type) = &split_part_type($stores);
                   3218: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3219: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3220: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3221: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3222: 	    $display =~ s/Number of Attempts/Tries/;
                   3223: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3224: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3225: 	    $columns{$partid}+=2;
                   3226: 	}
                   3227:     }
                   3228:     foreach my $partid (@partid) {
1.324     albertel 3229: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3230: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3231: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3232: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3233: 
1.44      ng       3234:     }
                   3235:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3236:     $result .= $header;
1.44      ng       3237:     $result .= '</tr>'."\n";
1.93      albertel 3238:     my $noupdate;
1.126     ng       3239:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3240:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3241: 	my $line;
1.257     albertel 3242: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3243: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3244: 	my %newrecord;
                   3245: 	my $updateflag = 0;
1.281     albertel 3246: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3247: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3248: 	if (!&canmodify($usec)) {
1.126     ng       3249: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3250: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3251: 	    next;
                   3252: 	}
1.269     raeburn  3253:         my %aggregate = ();
                   3254:         my $aggregateflag = 0;
1.281     albertel 3255: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3256: 	foreach (@partid) {
1.257     albertel 3257: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3258: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3259: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3260: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3261: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3262: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3263: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3264: 	    my $score;
                   3265: 	    if ($partial eq '') {
1.257     albertel 3266: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3267: 	    } elsif ($partial > 0) {
                   3268: 		$score = 'correct_by_override';
                   3269: 	    } elsif ($partial == 0) {
                   3270: 		$score = 'incorrect_by_override';
                   3271: 	    }
1.257     albertel 3272: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3273: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3274: 
1.292     albertel 3275: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3276: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3277: 	    if ($dropMenu eq 'reset status' &&
                   3278: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3279: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3280: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3281: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3282: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3283: 		$updateflag = 1;
1.269     raeburn  3284:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3285:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3286:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3287:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3288:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3289:                     $aggregateflag = 1;
                   3290:                 }
1.139     albertel 3291: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3292: 		$updateflag = 1;
                   3293: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3294: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3295: 		$rec_update++;
1.125     ng       3296: 	    }
                   3297: 
1.93      albertel 3298: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3299: 		'<td align="center">'.$awarded.
                   3300: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3301: 
1.54      albertel 3302: 
                   3303: 	    my $partid=$_;
                   3304: 	    foreach my $stores (@parts) {
                   3305: 		my ($part,$type) = &split_part_type($stores);
                   3306: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3307: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3308: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3309: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3310: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3311: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3312: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3313: 		    $updateflag=1;
                   3314: 		}
1.93      albertel 3315: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3316: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3317: 	    }
1.44      ng       3318: 	}
1.93      albertel 3319: 	$line.='</tr>'."\n";
1.301     albertel 3320: 
                   3321: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3322: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3323: 
1.44      ng       3324: 	if ($updateflag) {
                   3325: 	    $count++;
1.257     albertel 3326: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3327: 				    $udom,$uname);
1.301     albertel 3328: 
                   3329: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3330: 					      $cnum,$udom,$uname)) {
                   3331: 		# need to figure out if should be in queue.
                   3332: 		my %record =  
                   3333: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3334: 					     $udom,$uname);
                   3335: 		my $all_graded = 1;
                   3336: 		my $none_graded = 1;
                   3337: 		foreach my $part (@parts) {
                   3338: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3339: 			$all_graded = 0;
                   3340: 		    } else {
                   3341: 			$none_graded = 0;
                   3342: 		    }
                   3343: 		}
                   3344: 
                   3345: 		if ($all_graded || $none_graded) {
                   3346: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3347: 							   $symb,$cdom,$cnum,
                   3348: 							   $udom,$uname);
                   3349: 		}
                   3350: 	    }
                   3351: 
1.126     ng       3352: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3353: 	    $updateCtr++;
1.93      albertel 3354: 	} else {
1.126     ng       3355: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3356: 	    $noupdateCtr++;
1.44      ng       3357: 	}
1.269     raeburn  3358:         if ($aggregateflag) {
                   3359:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3360: 				  $cdom,$cnum);
1.269     raeburn  3361:         }
1.93      albertel 3362:     }
                   3363:     if ($noupdate) {
1.126     ng       3364: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3365: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3366: 	$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       3367:     }
1.72      ng       3368:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3369: 	&show_grading_menu_form ($symb);
1.125     ng       3370:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3371: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3372: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3373:     return $title.$msg.$result;
1.5       albertel 3374: }
1.54      albertel 3375: 
                   3376: sub split_part_type {
                   3377:     my ($partstr) = @_;
                   3378:     my ($temp,@allparts)=split(/_/,$partstr);
                   3379:     my $type=pop(@allparts);
                   3380:     my $part=join('.',@allparts);
                   3381:     return ($part,$type);
                   3382: }
                   3383: 
1.44      ng       3384: #------------- end of section for handling grading by section/class ---------
                   3385: #
                   3386: #----------------------------------------------------------------------------
                   3387: 
1.5       albertel 3388: 
1.44      ng       3389: #----------------------------------------------------------------------------
                   3390: #
                   3391: #-------------------------- Next few routines handles grading by csv upload
                   3392: #
                   3393: #--- Javascript to handle csv upload
1.27      albertel 3394: sub csvupload_javascript_reverse_associate {
1.246     albertel 3395:     my $error1=&mt('You need to specify the username or ID');
                   3396:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3397:   return(<<ENDPICK);
                   3398:   function verify(vf) {
                   3399:     var foundsomething=0;
                   3400:     var founduname=0;
1.243     albertel 3401:     var foundID=0;
1.27      albertel 3402:     for (i=0;i<=vf.nfields.value;i++) {
                   3403:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3404:       if (i==0 && tw!=0) { foundID=1; }
                   3405:       if (i==1 && tw!=0) { founduname=1; }
                   3406:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3407:     }
1.246     albertel 3408:     if (founduname==0 && foundID==0) {
                   3409: 	alert('$error1');
                   3410: 	return;
1.27      albertel 3411:     }
                   3412:     if (foundsomething==0) {
1.246     albertel 3413: 	alert('$error2');
                   3414: 	return;
1.27      albertel 3415:     }
                   3416:     vf.submit();
                   3417:   }
                   3418:   function flip(vf,tf) {
                   3419:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3420:     var i;
                   3421:     for (i=0;i<=vf.nfields.value;i++) {
                   3422:       //can not pick the same destination field for both name and domain
                   3423:       if (((i ==0)||(i ==1)) && 
                   3424:           ((tf==0)||(tf==1)) && 
                   3425:           (i!=tf) &&
                   3426:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3427:         eval('vf.f'+i+'.selectedIndex=0;')
                   3428:       }
                   3429:     }
                   3430:   }
                   3431: ENDPICK
                   3432: }
                   3433: 
                   3434: sub csvupload_javascript_forward_associate {
1.246     albertel 3435:     my $error1=&mt('You need to specify the username or ID');
                   3436:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3437:   return(<<ENDPICK);
                   3438:   function verify(vf) {
                   3439:     var foundsomething=0;
                   3440:     var founduname=0;
1.243     albertel 3441:     var foundID=0;
1.27      albertel 3442:     for (i=0;i<=vf.nfields.value;i++) {
                   3443:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3444:       if (tw==1) { foundID=1; }
                   3445:       if (tw==2) { founduname=1; }
                   3446:       if (tw>3) { foundsomething=1; }
1.27      albertel 3447:     }
1.246     albertel 3448:     if (founduname==0 && foundID==0) {
                   3449: 	alert('$error1');
                   3450: 	return;
1.27      albertel 3451:     }
                   3452:     if (foundsomething==0) {
1.246     albertel 3453: 	alert('$error2');
                   3454: 	return;
1.27      albertel 3455:     }
                   3456:     vf.submit();
                   3457:   }
                   3458:   function flip(vf,tf) {
                   3459:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3460:     var i;
                   3461:     //can not pick the same destination field twice
                   3462:     for (i=0;i<=vf.nfields.value;i++) {
                   3463:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3464:         eval('vf.f'+i+'.selectedIndex=0;')
                   3465:       }
                   3466:     }
                   3467:   }
                   3468: ENDPICK
                   3469: }
                   3470: 
1.26      albertel 3471: sub csvuploadmap_header {
1.324     albertel 3472:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3473:     my $javascript;
1.257     albertel 3474:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3475: 	$javascript=&csvupload_javascript_reverse_associate();
                   3476:     } else {
                   3477: 	$javascript=&csvupload_javascript_forward_associate();
                   3478:     }
1.45      ng       3479: 
1.324     albertel 3480:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3481:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3482:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3483:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3484:     $request->print(<<ENDPICK);
1.26      albertel 3485: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3486: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3487: $result
1.326     albertel 3488: <hr />
1.26      albertel 3489: <h3>Identify fields</h3>
                   3490: Total number of records found in file: $distotal <hr />
                   3491: Enter as many fields as you can. The system will inform you and bring you back
                   3492: to this page if the data selected is insufficient to run your class.<hr />
                   3493: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3494: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3495: <input type="hidden" name="associate"  value="" />
                   3496: <input type="hidden" name="phase"      value="three" />
                   3497: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3498: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3499: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3500: <input type="hidden" name="upfile_associate" 
1.257     albertel 3501:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3502: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3503: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3504: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3505: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3506: <hr />
                   3507: <script type="text/javascript" language="Javascript">
                   3508: $javascript
                   3509: </script>
                   3510: ENDPICK
1.118     ng       3511:     return '';
1.26      albertel 3512: 
                   3513: }
                   3514: 
                   3515: sub csvupload_fields {
1.324     albertel 3516:     my ($symb) = @_;
                   3517:     my (@parts) = &getpartlist($symb);
1.243     albertel 3518:     my @fields=(['ID','Student ID'],
                   3519: 		['username','Student Username'],
                   3520: 		['domain','Student Domain']);
1.324     albertel 3521:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3522:     foreach my $part (sort(@parts)) {
                   3523: 	my @datum;
                   3524: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3525: 	my $name=$part;
                   3526: 	if  (!$display) { $display = $name; }
                   3527: 	@datum=($name,$display);
1.244     albertel 3528: 	if ($name=~/^stores_(.*)_awarded/) {
                   3529: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3530: 	}
1.41      ng       3531: 	push(@fields,\@datum);
                   3532:     }
                   3533:     return (@fields);
1.26      albertel 3534: }
                   3535: 
                   3536: sub csvuploadmap_footer {
1.41      ng       3537:     my ($request,$i,$keyfields) =@_;
                   3538:     $request->print(<<ENDPICK);
1.26      albertel 3539: </table>
                   3540: <input type="hidden" name="nfields" value="$i" />
                   3541: <input type="hidden" name="keyfields" value="$keyfields" />
                   3542: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3543: </form>
                   3544: ENDPICK
                   3545: }
                   3546: 
1.283     albertel 3547: sub checkforfile_js {
1.86      ng       3548:     my $result =<<CSVFORMJS;
                   3549: <script type="text/javascript" language="javascript">
                   3550:     function checkUpload(formname) {
                   3551: 	if (formname.upfile.value == "") {
                   3552: 	    alert("Please use the browse button to select a file from your local directory.");
                   3553: 	    return false;
                   3554: 	}
                   3555: 	formname.submit();
                   3556:     }
                   3557:     </script>
                   3558: CSVFORMJS
1.283     albertel 3559:     return $result;
                   3560: }
                   3561: 
                   3562: sub upcsvScores_form {
                   3563:     my ($request) = shift;
1.324     albertel 3564:     my ($symb)=&get_symb($request);
1.283     albertel 3565:     if (!$symb) {return '';}
                   3566:     my $result=&checkforfile_js();
1.257     albertel 3567:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3568:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3569:     $result.=$table;
1.326     albertel 3570:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3571:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3572:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3573: 	'.</b></td></tr>'."\n";
                   3574:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3575:     my $upload=&mt("Upload Scores");
1.86      ng       3576:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3577:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3578:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3579:     $result.=<<ENDUPFORM;
1.106     albertel 3580: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3581: <input type="hidden" name="symb" value="$symb" />
                   3582: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3583: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3584: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3585: $upfile_select
1.370     www      3586: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3587: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3588: </form>
                   3589: ENDUPFORM
1.370     www      3590:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3591:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3592:     .'</td></tr></table>'."\n";
1.86      ng       3593:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3594:     $result.=&show_grading_menu_form($symb);
1.86      ng       3595:     return $result;
                   3596: }
                   3597: 
                   3598: 
1.26      albertel 3599: sub csvuploadmap {
1.41      ng       3600:     my ($request)= @_;
1.324     albertel 3601:     my ($symb)=&get_symb($request);
1.41      ng       3602:     if (!$symb) {return '';}
1.72      ng       3603: 
1.41      ng       3604:     my $datatoken;
1.257     albertel 3605:     if (!$env{'form.datatoken'}) {
1.41      ng       3606: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3607:     } else {
1.257     albertel 3608: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3609: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3610:     }
1.41      ng       3611:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3612:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3613:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3614:     my ($i,$keyfields);
                   3615:     if (@records) {
1.324     albertel 3616: 	my @fields=&csvupload_fields($symb);
1.45      ng       3617: 
1.257     albertel 3618: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3619: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3620: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3621: 							  \@fields);
                   3622: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3623: 	    chop($keyfields);
                   3624: 	} else {
                   3625: 	    unshift(@fields,['none','']);
                   3626: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3627: 							    \@fields);
1.311     banghart 3628:             foreach my $rec (@records) {
                   3629:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3630:                 if (%temp) {
                   3631:                     $keyfields=join(',',sort(keys(%temp)));
                   3632:                     last;
                   3633:                 }
                   3634:             }
1.41      ng       3635: 	}
                   3636:     }
                   3637:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3638:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3639: 
1.41      ng       3640:     return '';
1.27      albertel 3641: }
                   3642: 
1.246     albertel 3643: sub csvuploadoptions {
1.41      ng       3644:     my ($request)= @_;
1.324     albertel 3645:     my ($symb)=&get_symb($request);
1.257     albertel 3646:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3647:     my $ignore=&mt('Ignore First Line');
                   3648:     $request->print(<<ENDPICK);
                   3649: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3650: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3651: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3652: <!--
1.246     albertel 3653: <p>
                   3654: <label>
                   3655:    <input type="checkbox" name="show_full_results" />
                   3656:    Show a table of all changes
                   3657: </label>
                   3658: </p>
1.302     albertel 3659: -->
1.246     albertel 3660: <p>
                   3661: <label>
                   3662:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3663:    Overwrite any existing score
                   3664: </label>
                   3665: </p>
                   3666: ENDPICK
                   3667:     my %fields=&get_fields();
                   3668:     if (!defined($fields{'domain'})) {
1.257     albertel 3669: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3670: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3671:     }
1.257     albertel 3672:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3673: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3674: 	my $cleankey=$1;
                   3675: 	if ($cleankey eq 'command') { next; }
                   3676: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3677: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3678:     }
                   3679:     # FIXME do a check for any duplicated user ids...
                   3680:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3681:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3682: <hr /></form>'."\n");
1.324     albertel 3683:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3684:     return '';
                   3685: }
                   3686: 
                   3687: sub get_fields {
                   3688:     my %fields;
1.257     albertel 3689:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3690:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3691: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3692: 	    if ($env{'form.f'.$i} ne 'none') {
                   3693: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3694: 	    }
                   3695: 	} else {
1.257     albertel 3696: 	    if ($env{'form.f'.$i} ne 'none') {
                   3697: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3698: 	    }
                   3699: 	}
1.27      albertel 3700:     }
1.246     albertel 3701:     return %fields;
                   3702: }
                   3703: 
                   3704: sub csvuploadassign {
                   3705:     my ($request)= @_;
1.324     albertel 3706:     my ($symb)=&get_symb($request);
1.246     albertel 3707:     if (!$symb) {return '';}
1.345     bowersj2 3708:     my $error_msg = '';
1.246     albertel 3709:     &Apache::loncommon::load_tmp_file($request);
                   3710:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3711:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3712:     my %fields=&get_fields();
1.41      ng       3713:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3714:     my $courseid=$env{'request.course.id'};
1.97      albertel 3715:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3716:     my @notallowed;
1.41      ng       3717:     my @skipped;
                   3718:     my $countdone=0;
                   3719:     foreach my $grade (@gradedata) {
                   3720: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3721: 	my $domain;
                   3722: 	if ($entries{$fields{'domain'}}) {
                   3723: 	    $domain=$entries{$fields{'domain'}};
                   3724: 	} else {
1.257     albertel 3725: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3726: 	}
1.243     albertel 3727: 	$domain=~s/\s//g;
1.41      ng       3728: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3729: 	$username=~s/\s//g;
1.243     albertel 3730: 	if (!$username) {
                   3731: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3732: 	    $id=~s/\s//g;
1.243     albertel 3733: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3734: 	    $username=$ids{$id};
                   3735: 	}
1.41      ng       3736: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3737: 	    my $id=$entries{$fields{'ID'}};
                   3738: 	    $id=~s/\s//g;
                   3739: 	    if ($id) {
                   3740: 		push(@skipped,"$id:$domain");
                   3741: 	    } else {
                   3742: 		push(@skipped,"$username:$domain");
                   3743: 	    }
1.41      ng       3744: 	    next;
                   3745: 	}
1.108     albertel 3746: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3747: 	if (!&canmodify($usec)) {
                   3748: 	    push(@notallowed,"$username:$domain");
                   3749: 	    next;
                   3750: 	}
1.244     albertel 3751: 	my %points;
1.41      ng       3752: 	my %grades;
                   3753: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3754: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3755: 		$dest eq 'domain') { next; }
                   3756: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3757: 	    if ($dest=~/stores_(.*)_points/) {
                   3758: 		my $part=$1;
                   3759: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3760: 					      $symb,$domain,$username);
1.345     bowersj2 3761:                 if ($wgt) {
                   3762:                     $entries{$fields{$dest}}=~s/\s//g;
                   3763:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3764:                     my $award='correct_by_override';
                   3765:                     $grades{"resource.$part.awarded"}=$pcr;
                   3766:                     $grades{"resource.$part.solved"}=$award;
                   3767:                     $points{$part}=1;
                   3768:                 } else {
                   3769:                     $error_msg = "<br />" .
                   3770:                         &mt("Some point values were assigned"
                   3771:                             ." for problems with a weight "
                   3772:                             ."of zero. These values were "
                   3773:                             ."ignored.");
                   3774:                 }
1.244     albertel 3775: 	    } else {
                   3776: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3777: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3778: 		my $store_key=$dest;
                   3779: 		$store_key=~s/^stores/resource/;
                   3780: 		$store_key=~s/_/\./g;
                   3781: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3782: 	    }
1.41      ng       3783: 	}
1.398     albertel 3784: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3785: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.244     albertel 3786: #	&Apache::lonnet::logthis(" storing ".(join('-',%grades)));
1.302     albertel 3787: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3788: 					   $env{'request.course.id'},
                   3789: 					   $domain,$username);
                   3790: 	if ($result eq 'ok') {
                   3791: 	    $request->print('.');
                   3792: 	} else {
                   3793: 	    $request->print("<p>
1.398     albertel 3794:                               <span class=\"LC_error\">
                   3795:                                  Failed to save student $username:$domain.
                   3796:                                  Message when trying to save was ($result)
                   3797:                               </span>
1.302     albertel 3798:                              </p>" );
                   3799: 	}
1.41      ng       3800: 	$request->rflush();
                   3801: 	$countdone++;
                   3802:     }
1.398     albertel 3803:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3804:     if (@skipped) {
1.398     albertel 3805: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3806: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3807:     }
                   3808:     if (@notallowed) {
1.398     albertel 3809: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3810: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3811:     }
1.106     albertel 3812:     $request->print("<br />\n");
1.324     albertel 3813:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3814:     return $error_msg;
1.26      albertel 3815: }
1.44      ng       3816: #------------- end of section for handling csv file upload ---------
                   3817: #
                   3818: #-------------------------------------------------------------------
                   3819: #
1.122     ng       3820: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3821: #
                   3822: #--- Select a page/sequence and a student to grade
1.68      ng       3823: sub pickStudentPage {
                   3824:     my ($request) = shift;
                   3825: 
                   3826:     $request->print(<<LISTJAVASCRIPT);
                   3827: <script type="text/javascript" language="javascript">
                   3828: 
                   3829: function checkPickOne(formname) {
1.76      ng       3830:     if (radioSelection(formname.student) == null) {
1.68      ng       3831: 	alert("Please select the student you wish to grade.");
                   3832: 	return;
                   3833:     }
1.125     ng       3834:     ptr = pullDownSelection(formname.selectpage);
                   3835:     formname.page.value = formname["page"+ptr].value;
                   3836:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3837:     formname.submit();
                   3838: }
                   3839: 
                   3840: </script>
                   3841: LISTJAVASCRIPT
1.118     ng       3842:     &commonJSfunctions($request);
1.324     albertel 3843:     my ($symb) = &get_symb($request);
1.257     albertel 3844:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3845:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3846:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3847: 
1.398     albertel 3848:     my $result='<h3><span class="LC_info">&nbsp;'.
                   3849: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       3850: 
1.80      ng       3851:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3852:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 3853:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 3854:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3855: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3856: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3857:     my $ctr=0;
1.68      ng       3858:     foreach (@$titles) {
                   3859: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3860: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 3861: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       3862: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3863: 	$ctr++;
1.68      ng       3864:     }
1.326     albertel 3865:     $result.= '</select>'."<br />\n";
1.70      ng       3866:     $ctr=0;
                   3867:     foreach (@$titles) {
                   3868: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3869: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3870: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3871: 	$ctr++;
                   3872:     }
1.72      ng       3873:     $result.='<input type="hidden" name="page" />'."\n".
                   3874: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3875: 
1.401     albertel 3876:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 3877: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       3878: 
1.71      ng       3879:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 3880: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 3881: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 3882: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.432     banghart 3883:     
                   3884:     $result.=&build_section_inputs();
                   3885:     $result.='<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.72      ng       3886: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 3887: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 3888: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       3889: 
1.382     albertel 3890:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   3891: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   3892: 
1.80      ng       3893:     $result.='&nbsp;<input type="button" '.
1.126     ng       3894: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       3895: 
1.68      ng       3896:     $request->print($result);
                   3897: 
1.326     albertel 3898:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       3899: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3900: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       3901: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3902: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       3903: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3904: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       3905:  
1.76      ng       3906:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       3907:     my $ptr = 1;
1.294     albertel 3908:     foreach my $student (sort 
                   3909: 			 {
                   3910: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3911: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3912: 			     }
                   3913: 			     return $a cmp $b;
                   3914: 			 } (keys(%$fullname))) {
1.68      ng       3915: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       3916: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   3917: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 3918: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   3919: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       3920: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       3921: 	$ptr++;
                   3922:     }
1.381     albertel 3923:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   3924:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       3925:     $studentTable.='<input type="button" '.
                   3926: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       3927: 
1.324     albertel 3928:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       3929:     $request->print($studentTable);
                   3930: 
                   3931:     return '';
                   3932: }
                   3933: 
                   3934: sub getSymbMap {
1.132     bowersj2 3935:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       3936: 
                   3937:     my %symbx = ();
                   3938:     my @titles = ();
1.117     bowersj2 3939:     my $minder = 0;
                   3940: 
                   3941:     # Gather every sequence that has problems.
1.240     albertel 3942:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   3943: 					       1,0,1);
1.117     bowersj2 3944:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 3945: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 3946: 	    my $title = $minder.'.'.
                   3947: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   3948: 	    push(@titles, $title); # minder in case two titles are identical
                   3949: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 3950: 	    $minder++;
1.241     albertel 3951: 	}
1.68      ng       3952:     }
                   3953:     return \@titles,\%symbx;
                   3954: }
                   3955: 
1.72      ng       3956: #
                   3957: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       3958: sub displayPage {
                   3959:     my ($request) = shift;
                   3960: 
1.324     albertel 3961:     my ($symb) = &get_symb($request);
1.257     albertel 3962:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3963:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3964:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3965:     my $pageTitle = $env{'form.page'};
1.103     albertel 3966:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 3967:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   3968:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 3969: 
                   3970:     #need to make sure we have the correct data for later EXT calls, 
                   3971:     #thus invalidate the cache
                   3972:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3973:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3974:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3975:     &Apache::lonnet::clear_EXT_cache_status();
                   3976: 
1.103     albertel 3977:     if (!&canview($usec)) {
1.398     albertel 3978: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 3979: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 3980: 	return;
                   3981:     }
1.398     albertel 3982:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 3983:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       3984: 	'</h3>'."\n";
1.382     albertel 3985:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   3986: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   3987:     } else {
                   3988: 	delete($env{'form.CODE'});
                   3989:     }
1.71      ng       3990:     &sub_page_js($request);
                   3991:     $request->print($result);
                   3992: 
1.132     bowersj2 3993:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 3994:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       3995:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 3996:     if (!$map) {
1.398     albertel 3997: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 3998: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 3999: 	return; 
                   4000:     }
1.68      ng       4001:     my $iterator = $navmap->getIterator($map->map_start(),
                   4002: 					$map->map_finish());
                   4003: 
1.71      ng       4004:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4005: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4006: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4007: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4008: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4009: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4010: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4011: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4012: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4013: 
1.382     albertel 4014:     if (defined($env{'form.CODE'})) {
                   4015: 	$studentTable.=
                   4016: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4017:     }
1.381     albertel 4018:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4019: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4020: 	'/check.gif" height="16" border="0" />';
                   4021: 
1.118     ng       4022:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4023: 	' symbol.'."\n".
1.71      ng       4024: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4025: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4026: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4027: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4028: 
1.329     albertel 4029:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4030:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4031:     $iterator->next(); # skip the first BEGIN_MAP
                   4032:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4033:     while ($depth > 0) {
1.68      ng       4034:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4035:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4036: 
1.385     albertel 4037:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4038: 	    my $parts = $curRes->parts();
1.68      ng       4039:             my $title = $curRes->compTitle();
1.71      ng       4040: 	    my $symbx = $curRes->symb();
1.196     albertel 4041: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4042: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4043: 	    $studentTable.='<td valign="top">';
1.382     albertel 4044: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4045: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4046: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4047: 					     undef,'both',\%form);
1.71      ng       4048: 	    } else {
1.382     albertel 4049: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4050: 		$companswer =~ s|<form(.*?)>||g;
                   4051: 		$companswer =~ s|</form>||g;
1.71      ng       4052: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4053: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4054: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4055: #		}
1.116     ng       4056: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4057: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4058: 	    }
                   4059: 
1.257     albertel 4060: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4061: 
1.257     albertel 4062: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4063: 		if ($record{'version'} eq '') {
1.398     albertel 4064: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4065: 		} else {
1.116     ng       4066: 		    my %responseType = ();
                   4067: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4068: 			my @responseIds =$curRes->responseIds($partid);
                   4069: 			my @responseType =$curRes->responseType($partid);
                   4070: 			my %responseIds;
                   4071: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4072: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4073: 			}
                   4074: 			$responseType{$partid} = \%responseIds;
1.116     ng       4075: 		    }
1.148     albertel 4076: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4077: 
1.71      ng       4078: 		}
1.257     albertel 4079: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4080: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4081: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4082: 									$env{'request.course.id'},
1.71      ng       4083: 									'','.submission');
                   4084:  
                   4085: 	    }
1.103     albertel 4086: 	    if (&canmodify($usec)) {
                   4087: 		foreach my $partid (@{$parts}) {
                   4088: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4089: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4090: 		    $question++;
                   4091: 		}
1.196     albertel 4092: 		$prob++;
1.71      ng       4093: 	    }
                   4094: 	    $studentTable.='</td></tr>';
1.68      ng       4095: 
1.103     albertel 4096: 	}
1.68      ng       4097:         $curRes = $iterator->next();
                   4098:     }
                   4099: 
1.381     albertel 4100:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4101: 	'<input type="button" value="Save" '.
1.381     albertel 4102: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4103: 	'</form>'."\n";
1.324     albertel 4104:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4105:     $request->print($studentTable);
                   4106: 
                   4107:     return '';
1.119     ng       4108: }
                   4109: 
                   4110: sub displaySubByDates {
1.148     albertel 4111:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4112:     my $isCODE=0;
1.335     albertel 4113:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4114:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4115:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4116: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4117: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4118: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4119: 	'<td><b>Submission</b></td>'.
                   4120: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4121:     my ($version);
                   4122:     my %mark;
1.148     albertel 4123:     my %orders;
1.119     ng       4124:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4125:     if (!exists($$record{'1:timestamp'})) {
1.398     albertel 4126: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
1.147     albertel 4127:     }
1.335     albertel 4128: 
                   4129:     my $interaction;
1.119     ng       4130:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4131: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4132: 	if (exists($$record{$version.':resource.0.version'})) {
                   4133: 	    $interaction = $$record{$version.':resource.0.version'};
                   4134: 	}
                   4135: 
                   4136: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4137: 		             : "$version:resource");
                   4138: 	#&Apache::lonnet::logthis(" got $where");
1.119     ng       4139: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4140: 	if ($isCODE) {
                   4141: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4142: 	}
1.119     ng       4143: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4144: 	my @displaySub = ();
                   4145: 	foreach my $partid (@{$parts}) {
1.335     albertel 4146: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4147: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4148: 	    
                   4149: 
1.122     ng       4150: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4151: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4152: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4153: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4154: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4155: 
                   4156: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4157: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   4158: 		    #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
1.207     albertel 4159: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.398     albertel 4160: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
                   4161: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4162: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4163: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4164: 		    } else {
                   4165: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4166: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4167: 		    }
1.335     albertel 4168: 		    my $responseType=($isTask ? 'Task'
                   4169:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4170: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4171: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4172: 			$orders{$partid}->{$responseId}=
                   4173: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4174: 		    }
1.147     albertel 4175: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4176: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4177: 		}
                   4178: 	    }
1.335     albertel 4179: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4180: 		$displaySub[1].='Checked in by '.
                   4181: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4182: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4183: 		    '<br />';
                   4184: 	    }
                   4185: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4186: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4187: 		    lc($$record{"$where.$partid.award"}).' '.
                   4188: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4189: 		    '<br />';
                   4190: 	    }
1.335     albertel 4191: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4192: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4193: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4194: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4195: 		$displaySub[2].=
                   4196: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4197: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4198: 	    }
                   4199: 	}
                   4200: 	# needed because old essay regrader has not parts info
                   4201: 	if (exists $$record{"$version:resource.regrader"}) {
                   4202: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4203: 	}
                   4204: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4205: 	if ($displaySub[2]) {
                   4206: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4207: 	}
1.382     albertel 4208: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4209:     
1.119     ng       4210:     }
                   4211:     $studentTable.='</table></td></tr></table>';
                   4212:     return $studentTable;
1.71      ng       4213: }
                   4214: 
                   4215: sub updateGradeByPage {
                   4216:     my ($request) = shift;
                   4217: 
1.257     albertel 4218:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4219:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4220:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4221:     my $pageTitle = $env{'form.page'};
1.103     albertel 4222:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4223:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4224:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4225:     if (!&canmodify($usec)) {
1.398     albertel 4226: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4227: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4228: 	return;
                   4229:     }
1.398     albertel 4230:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4231:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4232: 	'</h3>'."\n";
1.70      ng       4233: 
1.68      ng       4234:     $request->print($result);
                   4235: 
1.132     bowersj2 4236:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4237:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4238:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4239:     if (!$map) {
1.398     albertel 4240: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4241: 	my ($symb)=&get_symb($request);
                   4242: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4243: 	return; 
                   4244:     }
1.71      ng       4245:     my $iterator = $navmap->getIterator($map->map_start(),
                   4246: 					$map->map_finish());
1.70      ng       4247: 
1.71      ng       4248:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4249: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4250: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4251: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4252: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4253: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4254: 
                   4255:     $iterator->next(); # skip the first BEGIN_MAP
                   4256:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4257:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4258:     while ($depth > 0) {
1.71      ng       4259:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4260:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4261: 
1.385     albertel 4262:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4263: 	    my $parts = $curRes->parts();
1.71      ng       4264:             my $title = $curRes->compTitle();
                   4265: 	    my $symbx = $curRes->symb();
1.196     albertel 4266: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4267: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4268: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4269: 
                   4270: 	    my %newrecord=();
                   4271: 	    my @displayPts=();
1.269     raeburn  4272:             my %aggregate = ();
                   4273:             my $aggregateflag = 0;
1.71      ng       4274: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4275: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4276: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4277: 
1.257     albertel 4278: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4279: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4280: 		my $partial = $newpts/$wgt;
                   4281: 		my $score;
                   4282: 		if ($partial > 0) {
                   4283: 		    $score = 'correct_by_override';
1.125     ng       4284: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4285: 		    $score = 'incorrect_by_override';
                   4286: 		}
1.257     albertel 4287: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4288: 		if ($dropMenu eq 'excused') {
1.71      ng       4289: 		    $partial = '';
                   4290: 		    $score = 'excused';
1.125     ng       4291: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4292: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4293: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4294: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4295: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4296: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4297: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4298: 		    $changeflag++;
                   4299: 		    $newpts = '';
1.269     raeburn  4300:                     
                   4301:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4302:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4303:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4304:                     if ($aggtries > 0) {
                   4305:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4306:                         $aggregateflag = 1;
                   4307:                     }
1.71      ng       4308: 		}
1.324     albertel 4309: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4310: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4311: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4312: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4313: 		    '&nbsp;<br />';
1.207     albertel 4314: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4315: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4316: 		    '&nbsp;<br />';
1.71      ng       4317: 		$question++;
1.380     albertel 4318: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4319: 
1.71      ng       4320: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4321: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4322: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4323: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4324: 
                   4325: 		$changeflag++;
                   4326: 	    }
                   4327: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4328: 		my %record = 
                   4329: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4330: 					     $udom,$uname);
                   4331: 
                   4332: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4333: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4334: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4335: 		    $newrecord{'resource.CODE'} = '';
                   4336: 		}
1.257     albertel 4337: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4338: 					$udom,$uname);
1.382     albertel 4339: 		%record = &Apache::lonnet::restore($symbx,
                   4340: 						   $env{'request.course.id'},
                   4341: 						   $udom,$uname);
1.380     albertel 4342: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4343: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4344: 	    }
1.380     albertel 4345: 	    
1.269     raeburn  4346:             if ($aggregateflag) {
                   4347:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4348:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4349:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4350:             }
1.125     ng       4351: 
1.71      ng       4352: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4353: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4354: 		'</tr>';
1.68      ng       4355: 
1.196     albertel 4356: 	    $prob++;
1.68      ng       4357: 	}
1.71      ng       4358:         $curRes = $iterator->next();
1.68      ng       4359:     }
1.98      albertel 4360: 
1.71      ng       4361:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4362:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4363:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4364: 		  'The scores were changed for '.
                   4365: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4366:     $request->print($grademsg.$studentTable);
1.68      ng       4367: 
1.70      ng       4368:     return '';
                   4369: }
                   4370: 
1.72      ng       4371: #-------- end of section for handling grading by page/sequence ---------
                   4372: #
                   4373: #-------------------------------------------------------------------
                   4374: 
1.75      albertel 4375: #--------------------Scantron Grading-----------------------------------
                   4376: #
                   4377: #------ start of section for handling grading by page/sequence ---------
                   4378: 
1.423     albertel 4379: =pod
                   4380: 
                   4381: =head1 Bubble sheet grading routines
                   4382: 
1.424     albertel 4383:   For this documentation:
                   4384: 
                   4385:    'scanline' refers to the full line of characters
                   4386:    from the file that we are parsing that represents one entire sheet
                   4387: 
                   4388:    'bubble line' refers to the data
                   4389:    representing the line of bubbles that are on the physical bubble sheet
                   4390: 
                   4391: 
                   4392: The overall process is that a scanned in bubble sheet data is uploaded
                   4393: into a course. When a user wants to grade, they select a
                   4394: sequence/folder of resources, a file of bubble sheet info, and pick
                   4395: one of the predefined configurations for what each scanline looks
                   4396: like.
                   4397: 
                   4398: Next each scanline is checked for any errors of either 'missing
                   4399: bubbles' (it's an error because it may have been missed scanned
                   4400: because too light bubbling), 'double bubble' (each bubble line should
                   4401: have no more that one letter picked), invalid or duplicated CODE,
                   4402: invalid student ID
                   4403: 
                   4404: If the CODE option is used that determines the randomization of the
                   4405: homework problems, either way the student ID is looked up into a
                   4406: username:domain.
                   4407: 
                   4408: During the validation phase the instructor can choose to skip scanlines. 
                   4409: 
                   4410: After the validation phase, there is now 3 bubble sheet files
                   4411: 
                   4412:   scantron_original_filename (unmodified original file)
                   4413:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4414:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4415: 
                   4416: Also there is a separate hash nohist_scantrondata that contains extra
                   4417: correction information that isn't representable in the bubble sheet
                   4418: file (see &scantron_getfile() for more information)
                   4419: 
                   4420: After all scanlines are either valid, marked as valid or skipped, then
                   4421: foreach line foreach problem in the picked sequence, an ssi request is
                   4422: made that simulates a user submitting their selected letter(s) against
                   4423: the homework problem.
1.423     albertel 4424: 
                   4425: =over 4
                   4426: 
                   4427: =cut
                   4428: 
                   4429: 
                   4430: =pod 
                   4431: 
                   4432: =item defaultFormData
                   4433: 
                   4434:   Returns html hidden inputs used to hold context/default values.
                   4435: 
                   4436:  Arguments:
                   4437:   $symb - $symb of the current resource 
                   4438: 
                   4439: =cut
1.422     foxr     4440: 
1.81      albertel 4441: sub defaultFormData {
1.324     albertel 4442:     my ($symb)=@_;
1.81      albertel 4443:     return '
1.418     albertel 4444:       <input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4445:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4446:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4447: }
                   4448: 
1.423     albertel 4449: =pod 
                   4450: 
                   4451: =item getSequenceDropDown
                   4452: 
                   4453:    Return html dropdown of possible sequences to grade
                   4454:  
                   4455:  Arguments:
                   4456:    $symb - $symb of the current resource 
                   4457: 
                   4458: =cut
1.422     foxr     4459: 
1.75      albertel 4460: sub getSequenceDropDown {
1.423     albertel 4461:     my ($symb)=@_;
1.75      albertel 4462:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4463:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4464:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4465:     my $ctr=0;
                   4466:     foreach (@$titles) {
                   4467: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4468: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4469: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4470: 	    '>'.$showtitle.'</option>'."\n";
                   4471: 	$ctr++;
                   4472:     }
                   4473:     $result.= '</select>';
                   4474:     return $result;
                   4475: }
                   4476: 
1.423     albertel 4477: 
                   4478: =pod 
                   4479: 
                   4480: =item scantron_filenames
                   4481: 
                   4482:    Returns a list of the scantron files in the current course 
                   4483: 
                   4484: =cut
1.422     foxr     4485: 
1.202     albertel 4486: sub scantron_filenames {
1.257     albertel 4487:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4488:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4489:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4490: 				    &propath($cdom,$cname));
1.202     albertel 4491:     my @possiblenames;
1.201     albertel 4492:     foreach my $filename (sort(@files)) {
1.157     albertel 4493: 	($filename)=split(/&/,$filename);
                   4494: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4495: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4496: 	push(@possiblenames,$filename);
                   4497:     }
                   4498:     return @possiblenames;
                   4499: }
                   4500: 
1.423     albertel 4501: =pod 
                   4502: 
                   4503: =item scantron_uploads
                   4504: 
                   4505:    Returns  html drop-down list of scantron files in current course.
                   4506: 
                   4507:  Arguments:
                   4508:    $file2grade - filename to set as selected in the dropdown
                   4509: 
                   4510: =cut
1.422     foxr     4511: 
1.202     albertel 4512: sub scantron_uploads {
1.209     ng       4513:     my ($file2grade) = @_;
1.202     albertel 4514:     my $result=	'<select name="scantron_selectfile">';
                   4515:     $result.="<option></option>";
                   4516:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4517: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4518:     }
                   4519:     $result.="</select>";
                   4520:     return $result;
                   4521: }
                   4522: 
1.423     albertel 4523: =pod 
                   4524: 
                   4525: =item scantron_scantab
                   4526: 
                   4527:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4528:   file.
                   4529: 
                   4530: =cut
1.422     foxr     4531: 
1.82      albertel 4532: sub scantron_scantab {
                   4533:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4534:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4535:     $result.='<option></option>'."\n";
1.82      albertel 4536:     foreach my $line (<$fh>) {
                   4537: 	my ($name,$descrip)=split(/:/,$line);
                   4538: 	if ($name =~ /^\#/) { next; }
                   4539: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4540:     }
                   4541:     $result.='</select>'."\n";
                   4542: 
                   4543:     return $result;
                   4544: }
                   4545: 
1.423     albertel 4546: =pod 
                   4547: 
                   4548: =item scantron_CODElist
                   4549: 
                   4550:   Returns html drop down of the saved CODE lists from current course,
                   4551:   generated from earlier printings.
                   4552: 
                   4553: =cut
1.422     foxr     4554: 
1.186     albertel 4555: sub scantron_CODElist {
1.257     albertel 4556:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4557:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4558:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4559:     my $namechoice='<option></option>';
1.225     albertel 4560:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4561: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4562: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4563: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4564:     }
                   4565:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4566:     return $namechoice;
                   4567: }
                   4568: 
1.423     albertel 4569: =pod 
                   4570: 
                   4571: =item scantron_CODEunique
                   4572: 
                   4573:   Returns the html for "Each CODE to be used once" radio.
                   4574: 
                   4575: =cut
1.422     foxr     4576: 
1.186     albertel 4577: sub scantron_CODEunique {
1.381     albertel 4578:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4579:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4580:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4581:                 </span>
                   4582:                 <span style="white-space: nowrap;">
1.272     albertel 4583:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4584:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4585:                 </span>';
1.186     albertel 4586:     return $result;
                   4587: }
1.423     albertel 4588: 
                   4589: =pod 
                   4590: 
                   4591: =item scantron_selectphase
                   4592: 
                   4593:   Generates the initial screen to start the bubble sheet process.
                   4594:   Allows for - starting a grading run.
1.424     albertel 4595:              - downloading existing scan data (original, corrected
1.423     albertel 4596:                                                 or skipped info)
                   4597: 
                   4598:              - uploading new scan data
                   4599: 
                   4600:  Arguments:
                   4601:   $r          - The Apache request object
                   4602:   $file2grade - name of the file that contain the scanned data to score
                   4603: 
                   4604: =cut
1.186     albertel 4605: 
1.75      albertel 4606: sub scantron_selectphase {
1.209     ng       4607:     my ($r,$file2grade) = @_;
1.324     albertel 4608:     my ($symb)=&get_symb($r);
1.75      albertel 4609:     if (!$symb) {return '';}
1.423     albertel 4610:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4611:     my $default_form_data=&defaultFormData($symb);
                   4612:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4613:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4614:     my $format_selector=&scantron_scantab();
1.186     albertel 4615:     my $CODE_selector=&scantron_CODElist();
                   4616:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4617:     my $result;
1.422     foxr     4618: 
                   4619:     # Chunk of form to prompt for a file to grade and how:
                   4620: 
1.75      albertel 4621:     $result.= <<SCANTRONFORM;
1.162     albertel 4622:     <table width="100%" border="0">
1.75      albertel 4623:     <tr>
1.226     albertel 4624:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4625:       <td bgcolor="#777777">
1.203     albertel 4626:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4627:         $default_form_data
1.75      albertel 4628:         <table width="100%" border="0">
                   4629:           <tr bgcolor="#e6ffff">
1.174     albertel 4630:             <td colspan="2">
                   4631:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4632:             </td>
                   4633:           </tr>
                   4634:           <tr bgcolor="#ffffe6">
1.174     albertel 4635:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4636:           </tr>
                   4637:           <tr bgcolor="#ffffe6">
1.174     albertel 4638:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4639:           </tr>
1.82      albertel 4640:           <tr bgcolor="#ffffe6">
1.174     albertel 4641:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4642:           </tr>
1.157     albertel 4643:           <tr bgcolor="#ffffe6">
1.186     albertel 4644:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4645:           </tr>
                   4646:           <tr bgcolor="#ffffe6">
                   4647:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4648:           </tr>
                   4649:           <tr bgcolor="#ffffe6">
1.187     albertel 4650: 	    <td> Options: </td>
                   4651:             <td>
1.272     albertel 4652: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4653:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4654:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4655: 	    </td>
                   4656:           </tr>
                   4657:           <tr bgcolor="#ffffe6">
1.174     albertel 4658:             <td colspan="2">
1.265     www      4659:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4660:             </td>
                   4661:           </tr>
                   4662:         </table>
1.226     albertel 4663:        </td>
                   4664:      </form>
1.162     albertel 4665:     </tr>
                   4666: SCANTRONFORM
                   4667:    
                   4668:     $r->print($result);
                   4669: 
1.257     albertel 4670:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4671:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4672: 
1.422     foxr     4673: 	# Chunk of form to prompt for a scantron file upload.
                   4674: 
1.162     albertel 4675:         $r->print(<<SCANTRONFORM);
                   4676:     <tr>
                   4677:       <td bgcolor="#777777">
                   4678:         <table width="100%" border="0">
                   4679:           <tr bgcolor="#e6ffff">
                   4680:             <td>
1.174     albertel 4681:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4682:             </td>
                   4683:           </tr>
                   4684:           <tr bgcolor="#ffffe6">
                   4685:             <td>
                   4686: SCANTRONFORM
1.324     albertel 4687:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4688:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4689:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4690:     $r->print(<<UPLOAD);
                   4691:               <script type="text/javascript" language="javascript">
                   4692:     function checkUpload(formname) {
                   4693: 	if (formname.upfile.value == "") {
                   4694: 	    alert("Please use the browse button to select a file from your local directory.");
                   4695: 	    return false;
                   4696: 	}
                   4697: 	formname.submit();
                   4698:     }
                   4699:               </script>
                   4700: 
                   4701:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4702:                 $default_form_data
                   4703:                 <input name='courseid' type='hidden' value='$cnum' />
                   4704:                 <input name='domainid' type='hidden' value='$cdom' />
                   4705:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4706:                 File to upload:<input type="file" name="upfile" size="50" />
                   4707:                 <br />
                   4708:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4709:               </form>
                   4710: UPLOAD
1.162     albertel 4711: 
                   4712:         $r->print(<<SCANTRONFORM);
                   4713:             </td>
                   4714:           </tr>
1.75      albertel 4715:         </table>
                   4716:       </td>
                   4717:     </tr>
1.162     albertel 4718: SCANTRONFORM
                   4719:     }
1.422     foxr     4720: 
                   4721:     # Chunk of the form that prompts to view a scoring office file,
                   4722:     # corrected file, skipped records in a file.
                   4723: 
1.187     albertel 4724:     $r->print(<<SCANTRONFORM);
                   4725:     <tr>
1.226     albertel 4726:       <form action='/adm/grades' name='scantron_download'>
                   4727:         <td bgcolor="#777777">
1.379     albertel 4728: 	  $default_form_data
1.187     albertel 4729:           <input type="hidden" name="command" value="scantron_download" />
                   4730:           <table width="100%" border="0">
                   4731:             <tr bgcolor="#e6ffff">
                   4732:               <td colspan="2">
                   4733:                 &nbsp;<b>Download a scoring office file</b>
                   4734:               </td>
                   4735:             </tr>
                   4736:             <tr bgcolor="#ffffe6">
                   4737:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4738:             </tr>
                   4739:             <tr bgcolor="#ffffe6">
                   4740:               <td colspan="2">
1.293     www      4741:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4742:               </td>
                   4743:             </tr>
                   4744:           </table>
1.226     albertel 4745:         </td>
                   4746:       </form>
1.187     albertel 4747:     </tr>
                   4748: SCANTRONFORM
1.162     albertel 4749: 
                   4750:     $r->print(<<SCANTRONFORM);
1.75      albertel 4751:   </table>
1.81      albertel 4752: $grading_menu_button
1.75      albertel 4753: SCANTRONFORM
                   4754: 
1.162     albertel 4755:     return
1.75      albertel 4756: }
                   4757: 
1.423     albertel 4758: =pod
                   4759: 
                   4760: =item get_scantron_config
                   4761: 
                   4762:    Parse and return the scantron configuration line selected as a
                   4763:    hash of configuration file fields.
                   4764: 
                   4765:  Arguments:
                   4766:     which - the name of the configuration to parse from the file.
                   4767: 
                   4768: 
                   4769:  Returns:
                   4770:             If the named configuration is not in the file, an empty
                   4771:             hash is returned.
                   4772:     a hash with the fields
                   4773:       name         - internal name for the this configuration setup
                   4774:       description  - text to display to operator that describes this config
                   4775:       CODElocation - if 0 or the string 'none'
                   4776:                           - no CODE exists for this config
                   4777:                      if -1 || the string 'letter'
                   4778:                           - a CODE exists for this config and is
                   4779:                             a string of letters
                   4780:                      Unsupported value (but planned for future support)
                   4781:                           if a positive integer
                   4782:                                - The CODE exists as the first n items from
                   4783:                                  the question section of the form
                   4784:                           if the string 'number'
                   4785:                                - The CODE exists for this config and is
                   4786:                                  a string of numbers
                   4787:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4788:                      the CODE starts
                   4789:       CODElength  - length of the CODE
                   4790:       IDstart     - column where the student ID number starts
                   4791:       IDlength    - length of the student ID info
                   4792:       Qstart      - column where the information from the bubbled
                   4793:                     'questions' start
                   4794:       Qlength     - number of columns comprising a single bubble line from
                   4795:                     the sheet. (usually either 1 or 10)
1.424     albertel 4796:       Qon         - either a single character representing the character used
1.423     albertel 4797:                     to signal a bubble was chosen in the positional setup, or
                   4798:                     the string 'letter' if the letter of the chosen bubble is
                   4799:                     in the final, or 'number' if a number representing the
                   4800:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 4801:       Qoff        - the character used to represent that a bubble was
                   4802:                     left blank
1.423     albertel 4803:       PaperID     - if the scanning process generates a unique number for each
                   4804:                     sheet scanned the column that this ID number starts in
                   4805:       PaperIDlength - number of columns that comprise the unique ID number
                   4806:                       for the sheet of paper
1.424     albertel 4807:       FirstName   - column that the first name starts in
1.423     albertel 4808:       FirstNameLength - number of columns that the first name spans
                   4809:  
                   4810:       LastName    - column that the last name starts in
                   4811:       LastNameLength - number of columns that the last name spans
                   4812: 
                   4813: =cut
1.422     foxr     4814: 
1.82      albertel 4815: sub get_scantron_config {
                   4816:     my ($which) = @_;
                   4817:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4818:     my %config;
1.157     albertel 4819:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4820:     foreach my $line (<$fh>) {
                   4821: 	my ($name,$descrip)=split(/:/,$line);
                   4822: 	if ($name ne $which ) { next; }
                   4823: 	chomp($line);
                   4824: 	my @config=split(/:/,$line);
                   4825: 	$config{'name'}=$config[0];
                   4826: 	$config{'description'}=$config[1];
                   4827: 	$config{'CODElocation'}=$config[2];
                   4828: 	$config{'CODEstart'}=$config[3];
                   4829: 	$config{'CODElength'}=$config[4];
                   4830: 	$config{'IDstart'}=$config[5];
                   4831: 	$config{'IDlength'}=$config[6];
                   4832: 	$config{'Qstart'}=$config[7];
                   4833: 	$config{'Qlength'}=$config[8];
                   4834: 	$config{'Qoff'}=$config[9];
                   4835: 	$config{'Qon'}=$config[10];
1.157     albertel 4836: 	$config{'PaperID'}=$config[11];
                   4837: 	$config{'PaperIDlength'}=$config[12];
                   4838: 	$config{'FirstName'}=$config[13];
                   4839: 	$config{'FirstNamelength'}=$config[14];
                   4840: 	$config{'LastName'}=$config[15];
                   4841: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4842: 	last;
                   4843:     }
                   4844:     return %config;
                   4845: }
                   4846: 
1.423     albertel 4847: =pod 
                   4848: 
                   4849: =item username_to_idmap
                   4850: 
                   4851:     creates a hash keyed by student id with values of the corresponding
                   4852:     student username:domain.
                   4853: 
                   4854:   Arguments:
                   4855: 
                   4856:     $classlist - reference to the class list hash. This is a hash
                   4857:                  keyed by student name:domain  whose elements are references
1.424     albertel 4858:                  to arrays containing various chunks of information
1.423     albertel 4859:                  about the student. (See loncoursedata for more info).
                   4860: 
                   4861:   Returns
                   4862:     %idmap - the constructed hash
                   4863: 
                   4864: =cut
                   4865: 
1.82      albertel 4866: sub username_to_idmap {
                   4867:     my ($classlist)= @_;
                   4868:     my %idmap;
                   4869:     foreach my $student (keys(%$classlist)) {
                   4870: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4871: 	    $student;
                   4872:     }
                   4873:     return %idmap;
                   4874: }
1.423     albertel 4875: 
                   4876: =pod
                   4877: 
1.424     albertel 4878: =item scantron_fixup_scanline
1.423     albertel 4879: 
                   4880:    Process a requested correction to a scanline.
                   4881: 
                   4882:   Arguments:
                   4883:     $scantron_config   - hash from &get_scantron_config()
                   4884:     $scan_data         - hash of correction information 
                   4885:                           (see &scantron_getfile())
                   4886:     $line              - existing scanline
                   4887:     $whichline         - line number of the passed in scanline
                   4888:     $field             - type of change to process 
                   4889:                          (either 
                   4890:                           'ID'     -> correct the student ID number
                   4891:                           'CODE'   -> correct the CODE
                   4892:                           'answer' -> fixup the submitted answers)
                   4893:     
                   4894:    $args               - hash of additional info,
                   4895:                           - 'ID' 
                   4896:                                'newid' -> studentID to use in replacement
1.424     albertel 4897:                                           of existing one
1.423     albertel 4898:                           - 'CODE' 
                   4899:                                'CODE_ignore_dup' - set to true if duplicates
                   4900:                                                    should be ignored.
                   4901: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 4902:                                         if the existing unfound code should
1.423     albertel 4903:                                         be used as is
                   4904:                           - 'answer'
                   4905:                                'response' - new answer or 'none' if blank
                   4906:                                'question' - the bubble line to change
                   4907: 
                   4908:   Returns:
                   4909:     $line - the modified scanline
                   4910: 
                   4911:   Side effects: 
                   4912:     $scan_data - may be updated
                   4913: 
                   4914: =cut
                   4915: 
1.82      albertel 4916: 
1.157     albertel 4917: sub scantron_fixup_scanline {
                   4918:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.423     albertel 4919: 
1.157     albertel 4920:     if ($field eq 'ID') {
                   4921: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 4922: 	    return ($line,1,'New value too large');
1.157     albertel 4923: 	}
                   4924: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   4925: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   4926: 				     $args->{'newid'});
                   4927: 	}
                   4928: 	substr($line,$$scantron_config{'IDstart'}-1,
                   4929: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   4930: 	if ($args->{'newid'}=~/^\s*$/) {
                   4931: 	    &scan_data($scan_data,"$whichline.user",
                   4932: 		       $args->{'username'}.':'.$args->{'domain'});
                   4933: 	}
1.186     albertel 4934:     } elsif ($field eq 'CODE') {
1.192     albertel 4935: 	if ($args->{'CODE_ignore_dup'}) {
                   4936: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   4937: 	}
                   4938: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   4939: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 4940: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   4941: 		return ($line,1,'New CODE value too large');
                   4942: 	    }
                   4943: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   4944: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   4945: 	    }
                   4946: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   4947: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 4948: 	}
1.157     albertel 4949:     } elsif ($field eq 'answer') {
                   4950: 	my $length=$scantron_config->{'Qlength'};
                   4951: 	my $off=$scantron_config->{'Qoff'};
                   4952: 	my $on=$scantron_config->{'Qon'};
                   4953: 	my $answer=${off}x$length;
                   4954: 	if ($args->{'response'} eq 'none') {
                   4955: 	    &scan_data($scan_data,
                   4956: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   4957: 	} else {
1.274     albertel 4958: 	    if ($on eq 'letter') {
                   4959: 		my @alphabet=('A'..'Z');
                   4960: 		$answer=$alphabet[$args->{'response'}];
                   4961: 	    } elsif ($on eq 'number') {
                   4962: 		$answer=$args->{'response'}+1;
1.389     albertel 4963: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 4964: 	    } else {
                   4965: 		substr($answer,$args->{'response'},1)=$on;
                   4966: 	    }
1.157     albertel 4967: 	    &scan_data($scan_data,
                   4968: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   4969: 	}
                   4970: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   4971: 	substr($line,$where-1,$length)=$answer;
                   4972:     }
                   4973:     return $line;
                   4974: }
1.423     albertel 4975: 
                   4976: =pod
                   4977: 
                   4978: =item scan_data
                   4979: 
                   4980:     Edit or look up  an item in the scan_data hash.
                   4981: 
                   4982:   Arguments:
                   4983:     $scan_data  - The hash (see scantron_getfile)
                   4984:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 4985:                   scantronfilename_key).
1.423     albertel 4986:     $data        - New value of the hash entry.
                   4987:     $delete      - If true, the entry is removed from the hash.
                   4988: 
                   4989:   Returns:
                   4990:     The new value of the hash table field (undefined if deleted).
                   4991: 
                   4992: =cut
                   4993: 
                   4994: 
1.157     albertel 4995: sub scan_data {
                   4996:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 4997:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 4998:     if (defined($value)) {
                   4999: 	$scan_data->{$filename.'_'.$key} = $value;
                   5000:     }
                   5001:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5002:     return $scan_data->{$filename.'_'.$key};
                   5003: }
1.423     albertel 5004: 
                   5005: =pod 
                   5006: 
                   5007: =item scantron_parse_scanline
                   5008: 
                   5009:   Decodes a scanline from the selected scantron file
                   5010: 
                   5011:  Arguments:
                   5012:     line             - The text of the scantron file line to process
                   5013:     whichline        - Line number
                   5014:     scantron_config  - Hash describing the format of the scantron lines.
                   5015:     scan_data        - Hash of extra information about the scanline
                   5016:                        (see scantron_getfile for more information)
                   5017:     just_header      - True if should not process question answers but only
                   5018:                        the stuff to the left of the answers.
                   5019:  Returns:
                   5020:    Hash containing the result of parsing the scanline
                   5021: 
                   5022:    Keys are all proceeded by the string 'scantron.'
                   5023: 
                   5024:        CODE    - the CODE in use for this scanline
                   5025:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5026:                  by the operator
                   5027:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5028:                             CODEs were selected, but the usage has been
                   5029:                             forced by the operator
                   5030:        ID  - student ID
                   5031:        PaperID - if used, the ID number printed on the sheet when the 
                   5032:                  paper was scanned
                   5033:        FirstName - first name from the sheet
                   5034:        LastName  - last name from the sheet
                   5035: 
                   5036:      if just_header was not true these key may also exist
                   5037: 
                   5038:        missingerror - a list of bubbled line numbers that had a blank bubble
                   5039:                       that is considered an error (if the operator had already
                   5040:                       okayed a blank bubble line as really being blank then
                   5041:                       that bubble line number won't appear here.
                   5042:        doubleerror  - a list of bubbled line numbers that had more than one
                   5043:                       bubble filled in and has not been corrected by the
                   5044:                       operator
                   5045:        maxquest     - the number of the last bubble line that was parsed
                   5046: 
                   5047:        (<number> starts at 1)
                   5048:        <number>.answer - zero or more letters representing the selected
                   5049:                          letters from the scanline for the bubble line 
                   5050:                          <number>.
                   5051:                          if blank there was either no bubble or there where
                   5052:                          multiple bubbles, (consult the keys missingerror and
                   5053:                          doubleerror if this is an error condition)
                   5054: 
                   5055: =cut
                   5056: 
1.82      albertel 5057: sub scantron_parse_scanline {
1.423     albertel 5058:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.82      albertel 5059:     my %record;
1.422     foxr     5060:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5061:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5062:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5063: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5064: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5065: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5066: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5067: 	    $record{'scantron.CODE'}=substr($data,
                   5068: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5069: 					    $$scantron_config{'CODElength'});
1.191     albertel 5070: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5071: 		$record{'scantron.useCODE'}=1;
                   5072: 	    }
1.192     albertel 5073: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5074: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5075: 	    }
1.82      albertel 5076: 	} else {
                   5077: 	    #FIXME interpret first N questions
                   5078: 	}
                   5079:     }
1.83      albertel 5080:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5081: 				  $$scantron_config{'IDlength'});
1.157     albertel 5082:     $record{'scantron.PaperID'}=
                   5083: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5084: 	       $$scantron_config{'PaperIDlength'});
                   5085:     $record{'scantron.FirstName'}=
                   5086: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5087: 	       $$scantron_config{'FirstNamelength'});
                   5088:     $record{'scantron.LastName'}=
                   5089: 	substr($data,$$scantron_config{'LastName'}-1,
                   5090: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5091:     if ($just_header) { return \%record; }
1.194     albertel 5092: 
1.82      albertel 5093:     my @alphabet=('A'..'Z');
                   5094:     my $questnum=0;
                   5095:     while ($questions) {
                   5096: 	$questnum++;
                   5097: 	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
                   5098: 	substr($questions,0,$$scantron_config{'Qlength'})='';
1.83      albertel 5099: 	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
1.239     albertel 5100: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.371     albertel 5101: 	    if ($currentquest eq '?'
                   5102: 		|| $currentquest eq '*') {
1.274     albertel 5103: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5104: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 5105: 	    } elsif (!defined($currentquest)
1.274     albertel 5106: 		     || $currentquest eq $$scantron_config{'Qoff'}
                   5107: 		     || $currentquest !~ /^[A-Z]$/) {
1.239     albertel 5108: 		$record{"scantron.$questnum.answer"}='';
                   5109: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5110: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5111: 		}
                   5112: 	    } else {
                   5113: 		$record{"scantron.$questnum.answer"}=$currentquest;
                   5114: 	    }
                   5115: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.371     albertel 5116: 	    if ($currentquest eq '?'
                   5117: 		|| $currentquest eq '*') {
1.274     albertel 5118: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5119: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 5120: 	    } elsif (!defined($currentquest)
                   5121: 		     || $currentquest eq $$scantron_config{'Qoff'} 
                   5122: 		     || $currentquest !~ /^\d$/) {
1.239     albertel 5123: 		$record{"scantron.$questnum.answer"}='';
                   5124: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5125: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5126: 		}
                   5127: 	    } else {
1.371     albertel 5128: 		# wrap zero back to J
                   5129: 		if ($currentquest eq '0') {
                   5130: 		    $record{"scantron.$questnum.answer"}=
                   5131: 			$alphabet[9];
                   5132: 		} else {
                   5133: 		    $record{"scantron.$questnum.answer"}=
                   5134: 			$alphabet[$currentquest-1];
                   5135: 		}
1.239     albertel 5136: 	    }
1.82      albertel 5137: 	} else {
1.239     albertel 5138: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
                   5139: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}) {
                   5140: 		$record{"scantron.$questnum.answer"}='';
                   5141: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5142: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5143: 		}
                   5144: 	    } else {
                   5145: 		$record{"scantron.$questnum.answer"}=
                   5146: 		    $alphabet[length($array[0])];
                   5147: 	    }
                   5148: 	    if (scalar(@array) gt 2) {
                   5149: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5150: 		my @ans=@array;
                   5151: 		my $i=length($ans[0]);shift(@ans);
                   5152: 		while ($#ans) {
                   5153: 		    $i+=length($ans[0])+1;
                   5154: 		    $record{"scantron.$questnum.answer"}.=$alphabet[$i];
                   5155: 		    shift(@ans);
                   5156: 		}
                   5157: 	    }
1.82      albertel 5158: 	}
                   5159:     }
1.83      albertel 5160:     $record{'scantron.maxquest'}=$questnum;
                   5161:     return \%record;
1.82      albertel 5162: }
                   5163: 
1.423     albertel 5164: =pod
                   5165: 
                   5166: =item scantron_add_delay
                   5167: 
                   5168:    Adds an error message that occurred during the grading phase to a
                   5169:    queue of messages to be shown after grading pass is complete
                   5170: 
                   5171:  Arguments:
1.424     albertel 5172:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5173:    $scanline    - the scanline that caused the error
                   5174:    $errormesage - the error message
                   5175:    $errorcode   - a numeric code for the error
                   5176: 
                   5177:  Side Effects:
1.424     albertel 5178:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5179: 
                   5180: =cut
                   5181: 
1.82      albertel 5182: sub scantron_add_delay {
1.140     albertel 5183:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5184:     push(@$delayqueue,
                   5185: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5186: 	  'ecode' => $errorcode }
                   5187: 	 );
1.82      albertel 5188: }
                   5189: 
1.423     albertel 5190: =pod
                   5191: 
                   5192: =item scantron_find_student
                   5193: 
1.424     albertel 5194:    Finds the username for the current scanline
                   5195: 
                   5196:   Arguments:
                   5197:    $scantron_record - hash result from scantron_parse_scanline
                   5198:    $scan_data       - hash of correction information 
                   5199:                       (see &scantron_getfile() form more information)
                   5200:    $idmap           - hash from &username_to_idmap()
                   5201:    $line            - number of current scanline
                   5202:  
                   5203:   Returns:
                   5204:    Either 'username:domain' or undef if unknown
                   5205: 
1.423     albertel 5206: =cut
                   5207: 
1.82      albertel 5208: sub scantron_find_student {
1.157     albertel 5209:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5210:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5211:     if ($scanID =~ /^\s*$/) {
                   5212:  	return &scan_data($scan_data,"$line.user");
                   5213:     }
1.83      albertel 5214:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5215:  	if (lc($id) eq lc($scanID)) {
                   5216:  	    return $$idmap{$id};
                   5217:  	}
1.83      albertel 5218:     }
                   5219:     return undef;
                   5220: }
                   5221: 
1.423     albertel 5222: =pod
                   5223: 
                   5224: =item scantron_filter
                   5225: 
1.424     albertel 5226:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5227:    hidden resources was selected
                   5228: 
1.423     albertel 5229: =cut
                   5230: 
1.83      albertel 5231: sub scantron_filter {
                   5232:     my ($curres)=@_;
1.331     albertel 5233: 
                   5234:     if (ref($curres) && $curres->is_problem()) {
                   5235: 	# if the user has asked to not have either hidden
                   5236: 	# or 'randomout' controlled resources to be graded
                   5237: 	# don't include them
                   5238: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5239: 	    && $curres->randomout) {
                   5240: 	    return 0;
                   5241: 	}
1.83      albertel 5242: 	return 1;
                   5243:     }
                   5244:     return 0;
1.82      albertel 5245: }
                   5246: 
1.423     albertel 5247: =pod
                   5248: 
                   5249: =item scantron_process_corrections
                   5250: 
1.424     albertel 5251:    Gets correction information out of submitted form data and corrects
                   5252:    the scanline
                   5253: 
1.423     albertel 5254: =cut
                   5255: 
1.157     albertel 5256: sub scantron_process_corrections {
                   5257:     my ($r) = @_;
1.257     albertel 5258:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5259:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5260:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5261:     my $which=$env{'form.scantron_line'};
1.200     albertel 5262:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5263:     my ($skip,$err,$errmsg);
1.257     albertel 5264:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5265: 	$skip=1;
1.257     albertel 5266:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5267: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5268: 	    $env{'form.scantron_domain'};
1.157     albertel 5269: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5270: 	($line,$err,$errmsg)=
                   5271: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5272: 				     'ID',{'newid'=>$newid,
1.257     albertel 5273: 				    'username'=>$env{'form.scantron_username'},
                   5274: 				    'domain'=>$env{'form.scantron_domain'}});
                   5275:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5276: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5277: 	my $newCODE;
1.192     albertel 5278: 	my %args;
1.190     albertel 5279: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5280: 	    $newCODE='use_unfound';
1.190     albertel 5281: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5282: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5283: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5284: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5285: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5286: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5287: 	}
1.257     albertel 5288: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5289: 	    $args{'CODE_ignore_dup'}=1;
                   5290: 	}
                   5291: 	$args{'CODE'}=$newCODE;
1.186     albertel 5292: 	($line,$err,$errmsg)=
                   5293: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5294: 				     'CODE',\%args);
1.257     albertel 5295:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5296: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5297: 	    ($line,$err,$errmsg)=
                   5298: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5299: 					 $which,'answer',
                   5300: 					 { 'question'=>$question,
1.257     albertel 5301: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5302: 	    if ($err) { last; }
                   5303: 	}
                   5304:     }
                   5305:     if ($err) {
1.398     albertel 5306: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5307:     } else {
1.200     albertel 5308: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5309: 	&scantron_putfile($scanlines,$scan_data);
                   5310:     }
                   5311: }
                   5312: 
1.423     albertel 5313: =pod
                   5314: 
                   5315: =item reset_skipping_status
                   5316: 
1.424     albertel 5317:    Forgets the current set of remember skipped scanlines (and thus
                   5318:    reverts back to considering all lines in the
                   5319:    scantron_skipped_<filename> file)
                   5320: 
1.423     albertel 5321: =cut
                   5322: 
1.200     albertel 5323: sub reset_skipping_status {
                   5324:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5325:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5326:     &scantron_putfile(undef,$scan_data);
                   5327: }
                   5328: 
1.423     albertel 5329: =pod
                   5330: 
                   5331: =item start_skipping
                   5332: 
1.424     albertel 5333:    Marks a scanline to be skipped. 
                   5334: 
1.423     albertel 5335: =cut
                   5336: 
1.376     albertel 5337: sub start_skipping {
1.200     albertel 5338:     my ($scan_data,$i)=@_;
                   5339:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5340:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5341: 	$remembered{$i}=2;
                   5342:     } else {
                   5343: 	$remembered{$i}=1;
                   5344:     }
1.200     albertel 5345:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5346: }
                   5347: 
1.423     albertel 5348: =pod
                   5349: 
                   5350: =item should_be_skipped
                   5351: 
1.424     albertel 5352:    Checks whether a scanline should be skipped.
                   5353: 
1.423     albertel 5354: =cut
                   5355: 
1.200     albertel 5356: sub should_be_skipped {
1.376     albertel 5357:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5358:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5359: 	# not redoing old skips
1.376     albertel 5360: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5361: 	return 0;
                   5362:     }
                   5363:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5364: 
                   5365:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5366: 	return 0;
                   5367:     }
1.200     albertel 5368:     return 1;
                   5369: }
                   5370: 
1.423     albertel 5371: =pod
                   5372: 
                   5373: =item remember_current_skipped
                   5374: 
1.424     albertel 5375:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5376:    file and remembers them into scan_data for later use.
                   5377: 
1.423     albertel 5378: =cut
                   5379: 
1.200     albertel 5380: sub remember_current_skipped {
                   5381:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5382:     my %to_remember;
                   5383:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5384: 	if ($scanlines->{'skipped'}[$i]) {
                   5385: 	    $to_remember{$i}=1;
                   5386: 	}
                   5387:     }
1.376     albertel 5388: 
1.200     albertel 5389:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5390:     &scantron_putfile(undef,$scan_data);
                   5391: }
                   5392: 
1.423     albertel 5393: =pod
                   5394: 
                   5395: =item check_for_error
                   5396: 
1.424     albertel 5397:     Checks if there was an error when attempting to remove a specific
                   5398:     scantron_.. bubble sheet data file. Prints out an error if
                   5399:     something went wrong.
                   5400: 
1.423     albertel 5401: =cut
                   5402: 
1.200     albertel 5403: sub check_for_error {
                   5404:     my ($r,$result)=@_;
                   5405:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5406: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5407:     }
                   5408: }
1.157     albertel 5409: 
1.423     albertel 5410: =pod
                   5411: 
                   5412: =item scantron_warning_screen
                   5413: 
1.424     albertel 5414:    Interstitial screen to make sure the operator has selected the
                   5415:    correct options before we start the validation phase.
                   5416: 
1.423     albertel 5417: =cut
                   5418: 
1.203     albertel 5419: sub scantron_warning_screen {
                   5420:     my ($button_text)=@_;
1.257     albertel 5421:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5422:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5423:     my $CODElist;
1.284     albertel 5424:     if ($scantron_config{'CODElocation'} &&
                   5425: 	$scantron_config{'CODEstart'} &&
                   5426: 	$scantron_config{'CODElength'}) {
                   5427: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5428: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5429: 	$CODElist=
                   5430: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5431: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5432:     }
1.203     albertel 5433:     return (<<STUFF);
                   5434: <p>
1.398     albertel 5435: <span class="LC_warning">Please double check the information
                   5436:                  below before clicking on '$button_text'</span>
1.203     albertel 5437: </p>
                   5438: <table>
1.284     albertel 5439: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5440: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5441: $CODElist
1.203     albertel 5442: </table>
                   5443: <br />
                   5444: <p> If this information is correct, please click on '$button_text'.</p>
                   5445: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5446: 
                   5447: <br />
                   5448: STUFF
                   5449: }
                   5450: 
1.423     albertel 5451: =pod
                   5452: 
                   5453: =item scantron_do_warning
                   5454: 
1.424     albertel 5455:    Check if the operator has picked something for all required
                   5456:    fields. Error out if something is missing.
                   5457: 
1.423     albertel 5458: =cut
                   5459: 
1.203     albertel 5460: sub scantron_do_warning {
                   5461:     my ($r)=@_;
1.324     albertel 5462:     my ($symb)=&get_symb($r);
1.203     albertel 5463:     if (!$symb) {return '';}
1.324     albertel 5464:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5465:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5466:     if ( $env{'form.selectpage'} eq '' ||
                   5467: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5468: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5469: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5470: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5471: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5472: 	} 
1.257     albertel 5473: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5474: 	    $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 5475: 	} 
1.257     albertel 5476: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5477: 	    $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 5478: 	} 
                   5479:     } else {
1.265     www      5480: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5481: 	$r->print(<<STUFF);
1.203     albertel 5482: $warning
1.265     www      5483: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5484: <input type="hidden" name="command" value="scantron_validate" />
                   5485: STUFF
1.237     albertel 5486:     }
1.352     albertel 5487:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5488:     return '';
                   5489: }
                   5490: 
1.423     albertel 5491: =pod
                   5492: 
                   5493: =item scantron_form_start
                   5494: 
1.424     albertel 5495:     html hidden input for remembering all selected grading options
                   5496: 
1.423     albertel 5497: =cut
                   5498: 
1.203     albertel 5499: sub scantron_form_start {
                   5500:     my ($max_bubble)=@_;
                   5501:     my $result= <<SCANTRONFORM;
                   5502: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5503:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5504:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5505:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5506:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5507:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5508:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5509:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5510:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5511:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5512: SCANTRONFORM
                   5513:     return $result;
                   5514: }
                   5515: 
1.423     albertel 5516: =pod
                   5517: 
                   5518: =item scantron_validate_file
                   5519: 
1.424     albertel 5520:     Dispatch routine for doing validation of a bubble sheet data file.
                   5521: 
                   5522:     Also processes any necessary information resets that need to
                   5523:     occur before validation begins (ignore previous corrections,
                   5524:     restarting the skipped records processing)
                   5525: 
1.423     albertel 5526: =cut
                   5527: 
1.157     albertel 5528: sub scantron_validate_file {
                   5529:     my ($r) = @_;
1.324     albertel 5530:     my ($symb)=&get_symb($r);
1.157     albertel 5531:     if (!$symb) {return '';}
1.324     albertel 5532:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5533:     
                   5534:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5535:     # them when doing the corrections reset
1.257     albertel 5536:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5537: 	&reset_skipping_status();
                   5538:     }
1.257     albertel 5539:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5540: 	&remember_current_skipped();
1.257     albertel 5541: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5542:     }
                   5543: 
1.257     albertel 5544:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5545: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5546: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5547: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5548: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5549:     }
1.200     albertel 5550: 
1.257     albertel 5551:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5552: 	&scantron_process_corrections($r);
                   5553:     }
1.424     albertel 5554:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5555:     #get the student pick code ready
                   5556:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5557:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5558:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5559:     $r->print($result);
                   5560:     
1.334     albertel 5561:     my @validate_phases=( 'sequence',
                   5562: 			  'ID',
1.157     albertel 5563: 			  'CODE',
                   5564: 			  'doublebubble',
                   5565: 			  'missingbubbles');
1.257     albertel 5566:     if (!$env{'form.validatepass'}) {
                   5567: 	$env{'form.validatepass'} = 0;
1.157     albertel 5568:     }
1.257     albertel 5569:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5570: 
                   5571:     my $stop=0;
                   5572:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5573: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5574: 	$r->rflush();
                   5575: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5576: 	{
                   5577: 	    no strict 'refs';
                   5578: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5579: 	}
                   5580:     }
                   5581:     if (!$stop) {
1.203     albertel 5582: 	my $warning=&scantron_warning_screen('Start Grading');
                   5583: 	$r->print(<<STUFF);
                   5584: Validation process complete.<br />
                   5585: $warning
                   5586: <input type="submit" name="submit" value="Start Grading" />
                   5587: <input type="hidden" name="command" value="scantron_process" />
                   5588: STUFF
                   5589: 
1.157     albertel 5590:     } else {
                   5591: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5592: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5593:     }
                   5594:     if ($stop) {
1.334     albertel 5595: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5596: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5597: 	    $r->print(' this error <br />');
                   5598: 
                   5599: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5600: 	} else {
                   5601: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5602: 	    $r->print(' using corrected info <br />');
                   5603: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5604: 	    $r->print(" this scanline saving it for later.");
                   5605: 	}
1.157     albertel 5606:     }
1.352     albertel 5607:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5608:     return '';
                   5609: }
                   5610: 
1.423     albertel 5611: 
                   5612: =pod
                   5613: 
                   5614: =item scantron_remove_file
                   5615: 
1.424     albertel 5616:    Removes the requested bubble sheet data file, makes sure that
                   5617:    scantron_original_<filename> is never removed
                   5618: 
                   5619: 
1.423     albertel 5620: =cut
                   5621: 
1.200     albertel 5622: sub scantron_remove_file {
1.192     albertel 5623:     my ($which)=@_;
1.257     albertel 5624:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5625:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5626:     my $file='scantron_';
1.200     albertel 5627:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5628: 	$file.=$which.'_';
1.192     albertel 5629:     } else {
                   5630: 	return 'refused';
                   5631:     }
1.257     albertel 5632:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5633:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5634: }
                   5635: 
1.423     albertel 5636: 
                   5637: =pod
                   5638: 
                   5639: =item scantron_remove_scan_data
                   5640: 
1.424     albertel 5641:    Removes all scan_data correction for the requested bubble sheet
                   5642:    data file.  (In the case that both the are doing skipped records we need
                   5643:    to remember the old skipped lines for the time being so that element
                   5644:    persists for a while.)
                   5645: 
1.423     albertel 5646: =cut
                   5647: 
1.200     albertel 5648: sub scantron_remove_scan_data {
1.257     albertel 5649:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5650:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5651:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5652:     my @todelete;
1.257     albertel 5653:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5654:     foreach my $key (@keys) {
                   5655: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5656: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5657: 		$key=~/remember_skipping/) {
                   5658: 		next;
                   5659: 	    }
1.192     albertel 5660: 	    push(@todelete,$key);
                   5661: 	}
                   5662:     }
1.200     albertel 5663:     my $result;
1.192     albertel 5664:     if (@todelete) {
1.200     albertel 5665: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5666:     }
                   5667:     return $result;
                   5668: }
                   5669: 
1.423     albertel 5670: 
                   5671: =pod
                   5672: 
                   5673: =item scantron_getfile
                   5674: 
1.424     albertel 5675:     Fetches the requested bubble sheet data file (all 3 versions), and
                   5676:     the scan_data hash
                   5677:   
                   5678:   Arguments:
                   5679:     None
                   5680: 
                   5681:   Returns:
                   5682:     2 hash references
                   5683: 
                   5684:      - first one has 
                   5685:          orig      -
                   5686:          corrected -
                   5687:          skipped   -  each of which points to an array ref of the specified
                   5688:                       file broken up into individual lines
                   5689:          count     - number of scanlines
                   5690:  
                   5691:      - second is the scan_data hash possible keys are
1.425     albertel 5692:        ($number refers to scanline numbered $number and thus the key affects
                   5693:         only that scanline
                   5694:         $bubline refers to the specific bubble line element and the aspects
                   5695:         refers to that specific bubble line element)
                   5696: 
                   5697:        $number.user - username:domain to use
                   5698:        $number.CODE_ignore_dup 
                   5699:                     - ignore the duplicate CODE error 
                   5700:        $number.useCODE
                   5701:                     - use the CODE in the scanline as is
                   5702:        $number.no_bubble.$bubline
                   5703:                     - it is valid that there is no bubbled in bubble
                   5704:                       at $number $bubline
                   5705:        remember_skipping
                   5706:                     - a frozen hash containing keys of $number and values
                   5707:                       of either 
                   5708:                         1 - we are on a 'do skipped records pass' and plan
                   5709:                             on processing this line
                   5710:                         2 - we are on a 'do skipped records pass' and this
                   5711:                             scanline has been marked to skip yet again
1.424     albertel 5712: 
1.423     albertel 5713: =cut
                   5714: 
1.157     albertel 5715: sub scantron_getfile {
1.200     albertel 5716:     #FIXME really would prefer a scantron directory
1.257     albertel 5717:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5718:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5719:     my $lines;
                   5720:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5721: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5722:     my %scanlines;
                   5723:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5724:     my $temp=$scanlines{'orig'};
                   5725:     $scanlines{'count'}=$#$temp;
                   5726: 
                   5727:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5728: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5729:     if ($lines eq '-1') {
                   5730: 	$scanlines{'corrected'}=[];
                   5731:     } else {
                   5732: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5733:     }
                   5734:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5735: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5736:     if ($lines eq '-1') {
                   5737: 	$scanlines{'skipped'}=[];
                   5738:     } else {
                   5739: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5740:     }
1.175     albertel 5741:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5742:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5743:     my %scan_data = @tmp;
                   5744:     return (\%scanlines,\%scan_data);
                   5745: }
                   5746: 
1.423     albertel 5747: =pod
                   5748: 
                   5749: =item lonnet_putfile
                   5750: 
1.424     albertel 5751:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   5752: 
                   5753:  Arguments:
                   5754:    $contents - data to store
                   5755:    $filename - filename to store $contents into
                   5756: 
                   5757:  Returns:
                   5758:    result value from &Apache::lonnet::finishuserfileupload
                   5759: 
1.423     albertel 5760: =cut
                   5761: 
1.157     albertel 5762: sub lonnet_putfile {
                   5763:     my ($contents,$filename)=@_;
1.257     albertel 5764:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5765:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5766:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 5767:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 5768: 
                   5769: }
                   5770: 
1.423     albertel 5771: =pod
                   5772: 
                   5773: =item scantron_putfile
                   5774: 
1.424     albertel 5775:     Stores the current version of the bubble sheet data files, and the
                   5776:     scan_data hash. (Does not modify the original version only the
                   5777:     corrected and skipped versions.
                   5778: 
                   5779:  Arguments:
                   5780:     $scanlines - hash ref that looks like the first return value from
                   5781:                  &scantron_getfile()
                   5782:     $scan_data - hash ref that looks like the second return value from
                   5783:                  &scantron_getfile()
                   5784: 
1.423     albertel 5785: =cut
                   5786: 
1.157     albertel 5787: sub scantron_putfile {
                   5788:     my ($scanlines,$scan_data) = @_;
1.200     albertel 5789:     #FIXME really would prefer a scantron directory
1.257     albertel 5790:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5791:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 5792:     if ($scanlines) {
                   5793: 	my $prefix='scantron_';
1.157     albertel 5794: # no need to update orig, shouldn't change
                   5795: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 5796: #		    $env{'form.scantron_selectfile'});
1.200     albertel 5797: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   5798: 			$prefix.'corrected_'.
1.257     albertel 5799: 			$env{'form.scantron_selectfile'});
1.200     albertel 5800: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   5801: 			$prefix.'skipped_'.
1.257     albertel 5802: 			$env{'form.scantron_selectfile'});
1.200     albertel 5803:     }
1.175     albertel 5804:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 5805: }
                   5806: 
1.423     albertel 5807: =pod
                   5808: 
                   5809: =item scantron_get_line
                   5810: 
1.424     albertel 5811:    Returns the correct version of the scanline
                   5812: 
                   5813:  Arguments:
                   5814:     $scanlines - hash ref that looks like the first return value from
                   5815:                  &scantron_getfile()
                   5816:     $scan_data - hash ref that looks like the second return value from
                   5817:                  &scantron_getfile()
                   5818:     $i         - number of the requested line (starts at 0)
                   5819: 
                   5820:  Returns:
                   5821:    A scanline, (either the original or the corrected one if it
                   5822:    exists), or undef if the requested scanline should be
                   5823:    skipped. (Either because it's an skipped scanline, or it's an
                   5824:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   5825:    pass.
                   5826: 
1.423     albertel 5827: =cut
                   5828: 
1.157     albertel 5829: sub scantron_get_line {
1.200     albertel 5830:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 5831:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   5832:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 5833:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   5834:     return $scanlines->{'orig'}[$i]; 
                   5835: }
                   5836: 
1.423     albertel 5837: =pod
                   5838: 
                   5839: =item scantron_todo_count
                   5840: 
1.424     albertel 5841:     Counts the number of scanlines that need processing.
                   5842: 
                   5843:  Arguments:
                   5844:     $scanlines - hash ref that looks like the first return value from
                   5845:                  &scantron_getfile()
                   5846:     $scan_data - hash ref that looks like the second return value from
                   5847:                  &scantron_getfile()
                   5848: 
                   5849:  Returns:
                   5850:     $count - number of scanlines to process
                   5851: 
1.423     albertel 5852: =cut
                   5853: 
1.200     albertel 5854: sub get_todo_count {
                   5855:     my ($scanlines,$scan_data)=@_;
                   5856:     my $count=0;
                   5857:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5858: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   5859: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5860: 	$count++;
                   5861:     }
                   5862:     return $count;
                   5863: }
                   5864: 
1.423     albertel 5865: =pod
                   5866: 
                   5867: =item scantron_put_line
                   5868: 
1.424     albertel 5869:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   5870:     data file.
                   5871: 
                   5872:  Arguments:
                   5873:     $scanlines - hash ref that looks like the first return value from
                   5874:                  &scantron_getfile()
                   5875:     $scan_data - hash ref that looks like the second return value from
                   5876:                  &scantron_getfile()
                   5877:     $i         - line number to update
                   5878:     $newline   - contents of the updated scanline
                   5879:     $skip      - if true make the line for skipping and update the
                   5880:                  'skipped' file
                   5881: 
1.423     albertel 5882: =cut
                   5883: 
1.157     albertel 5884: sub scantron_put_line {
1.200     albertel 5885:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 5886:     if ($skip) {
                   5887: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 5888: 	&start_skipping($scan_data,$i);
1.157     albertel 5889: 	return;
                   5890:     }
                   5891:     $scanlines->{'corrected'}[$i]=$newline;
                   5892: }
                   5893: 
1.423     albertel 5894: =pod
                   5895: 
                   5896: =item scantron_clear_skip
                   5897: 
1.424     albertel 5898:    Remove a line from the 'skipped' file
                   5899: 
                   5900:  Arguments:
                   5901:     $scanlines - hash ref that looks like the first return value from
                   5902:                  &scantron_getfile()
                   5903:     $scan_data - hash ref that looks like the second return value from
                   5904:                  &scantron_getfile()
                   5905:     $i         - line number to update
                   5906: 
1.423     albertel 5907: =cut
                   5908: 
1.376     albertel 5909: sub scantron_clear_skip {
                   5910:     my ($scanlines,$scan_data,$i)=@_;
                   5911:     if (exists($scanlines->{'skipped'}[$i])) {
                   5912: 	undef($scanlines->{'skipped'}[$i]);
                   5913: 	return 1;
                   5914:     }
                   5915:     return 0;
                   5916: }
                   5917: 
1.423     albertel 5918: =pod
                   5919: 
                   5920: =item scantron_filter_not_exam
                   5921: 
1.424     albertel 5922:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   5923:    filter out resources that are not marked as 'exam' mode
                   5924: 
1.423     albertel 5925: =cut
                   5926: 
1.334     albertel 5927: sub scantron_filter_not_exam {
                   5928:     my ($curres)=@_;
                   5929:     
                   5930:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   5931: 	# if the user has asked to not have either hidden
                   5932: 	# or 'randomout' controlled resources to be graded
                   5933: 	# don't include them
                   5934: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5935: 	    && $curres->randomout) {
                   5936: 	    return 0;
                   5937: 	}
                   5938: 	return 1;
                   5939:     }
                   5940:     return 0;
                   5941: }
                   5942: 
1.423     albertel 5943: =pod
                   5944: 
                   5945: =item scantron_validate_sequence
                   5946: 
1.424     albertel 5947:     Validates the selected sequence, checking for resource that are
                   5948:     not set to exam mode.
                   5949: 
1.423     albertel 5950: =cut
                   5951: 
1.334     albertel 5952: sub scantron_validate_sequence {
                   5953:     my ($r,$currentphase) = @_;
                   5954: 
                   5955:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5956:     my (undef,undef,$sequence)=
                   5957: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   5958: 
                   5959:     my $map=$navmap->getResourceByUrl($sequence);
                   5960: 
                   5961:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   5962:                                     value="ignore" />');
                   5963:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   5964: 	my @resources=
                   5965: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   5966: 	if (@resources) {
1.357     banghart 5967: 	    $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 5968: 	    return (1,$currentphase);
                   5969: 	}
                   5970:     }
                   5971: 
                   5972:     return (0,$currentphase+1);
                   5973: }
                   5974: 
1.423     albertel 5975: =pod
                   5976: 
                   5977: =item scantron_validate_ID
                   5978: 
1.424     albertel 5979:    Validates all scanlines in the selected file to not have any
                   5980:    invalid or underspecified student IDs
                   5981: 
1.423     albertel 5982: =cut
                   5983: 
1.157     albertel 5984: sub scantron_validate_ID {
                   5985:     my ($r,$currentphase) = @_;
                   5986:     
                   5987:     #get student info
                   5988:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5989:     my %idmap=&username_to_idmap($classlist);
                   5990: 
                   5991:     #get scantron line setup
1.257     albertel 5992:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5993:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5994: 
                   5995:     my %found=('ids'=>{},'usernames'=>{});
                   5996:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5997: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5998: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5999: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6000: 						 $scan_data);
                   6001: 	my $id=$$scan_record{'scantron.ID'};
                   6002: 	my $found;
                   6003: 	foreach my $checkid (keys(%idmap)) {
                   6004: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6005: 	}
                   6006: 	if ($found) {
                   6007: 	    my $username=$idmap{$found};
                   6008: 	    if ($found{'ids'}{$found}) {
                   6009: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6010: 					 $line,'duplicateID',$found);
1.194     albertel 6011: 		return(1,$currentphase);
1.157     albertel 6012: 	    } elsif ($found{'usernames'}{$username}) {
                   6013: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6014: 					 $line,'duplicateID',$username);
1.194     albertel 6015: 		return(1,$currentphase);
1.157     albertel 6016: 	    }
1.186     albertel 6017: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6018: 	    $found{'ids'}{$found}++;
                   6019: 	    $found{'usernames'}{$username}++;
                   6020: 	} else {
                   6021: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6022: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6023: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6024: 		    &scantron_get_correction($r,$i,$scan_record,
                   6025: 					     \%scantron_config,
                   6026: 					     $line,'duplicateID',$username);
1.194     albertel 6027: 		    return(1,$currentphase);
1.157     albertel 6028: 		} elsif (!defined($username)) {
                   6029: 		    &scantron_get_correction($r,$i,$scan_record,
                   6030: 					     \%scantron_config,
                   6031: 					     $line,'incorrectID');
1.194     albertel 6032: 		    return(1,$currentphase);
1.157     albertel 6033: 		}
                   6034: 		$found{'usernames'}{$username}++;
                   6035: 	    } else {
                   6036: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6037: 					 $line,'incorrectID');
1.194     albertel 6038: 		return(1,$currentphase);
1.157     albertel 6039: 	    }
                   6040: 	}
                   6041:     }
                   6042: 
                   6043:     return (0,$currentphase+1);
                   6044: }
                   6045: 
1.423     albertel 6046: =pod
                   6047: 
                   6048: =item scantron_get_correction
                   6049: 
1.424     albertel 6050:    Builds the interface screen to interact with the operator to fix a
                   6051:    specific error condition in a specific scanline
                   6052: 
                   6053:  Arguments:
                   6054:     $r           - Apache request object
                   6055:     $i           - number of the current scanline
                   6056:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6057:     $scan_config - hash ref as returned from &get_scantron_config()
                   6058:     $line        - full contents of the current scanline
                   6059:     $error       - error condition, valid values are
                   6060:                    'incorrectCODE', 'duplicateCODE',
                   6061:                    'doublebubble', 'missingbubble',
                   6062:                    'duplicateID', 'incorrectID'
                   6063:     $arg         - extra information needed
                   6064:        For errors:
                   6065:          - duplicateID   - paper number that this studentID was seen before on
                   6066:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6067:                            seen on before
                   6068:          - incorrectCODE - current incorrect CODE 
                   6069:          - doublebubble  - array ref of the bubble lines that have double
                   6070:                            bubble errors
                   6071:          - missingbubble - array ref of the bubble lines that have missing
                   6072:                            bubble errors
                   6073: 
1.423     albertel 6074: =cut
                   6075: 
1.157     albertel 6076: sub scantron_get_correction {
                   6077:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6078: 
                   6079: #FIXME in the case of a duplicated ID the previous line, probaly need
                   6080: #to show both the current line and the previous one and allow skipping
                   6081: #the previous one or the current one
                   6082: 
1.161     albertel 6083:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6084:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6085: 	$r->print(" for PaperID <tt>".
                   6086: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6087:     } else {
                   6088: 	$r->print(" in scanline $i <pre>".
                   6089: 		  $line."</pre> \n");
                   6090:     }
1.242     albertel 6091:     my $message="<p>The ID on the form is  <tt>".
                   6092: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6093: 	"The name on the paper is ".
                   6094: 	$$scan_record{'scantron.LastName'}.",".
                   6095: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6096: 
1.157     albertel 6097:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6098:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6099:     if ($error =~ /ID$/) {
1.186     albertel 6100: 	if ($error eq 'incorrectID') {
1.157     albertel 6101: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6102: 	} elsif ($error eq 'duplicateID') {
                   6103: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6104: 	}
1.242     albertel 6105: 	$r->print($message);
1.157     albertel 6106: 	$r->print("<p>How should I handle this? <br /> \n");
                   6107: 	$r->print("\n<ul><li> ");
                   6108: 	#FIXME it would be nice if this sent back the user ID and
                   6109: 	#could do partial userID matches
                   6110: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6111: 				       'scantron_username','scantron_domain'));
                   6112: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6113: 	$r->print("\n@".
1.257     albertel 6114: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6115: 
                   6116: 	$r->print('</li>');
1.186     albertel 6117:     } elsif ($error =~ /CODE$/) {
                   6118: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6119: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6120: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6121: 	    $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 6122: 	}
1.224     albertel 6123: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6124: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6125: 	$r->print($message);
1.186     albertel 6126: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6127: 	$r->print("\n<br /> ");
1.194     albertel 6128: 	my $i=0;
1.273     albertel 6129: 	if ($error eq 'incorrectCODE' 
                   6130: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6131: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6132: 	    if ($closest > 0) {
                   6133: 		foreach my $testcode (@{$closest}) {
                   6134: 		    my $checked='';
1.401     albertel 6135: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6136: 		    $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' />");
                   6137: 		    $r->print("\n<br />");
                   6138: 		    $i++;
                   6139: 		}
1.194     albertel 6140: 	    }
                   6141: 	}
1.273     albertel 6142: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6143: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6144: 	    $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>");
                   6145: 	    $r->print("\n<br />");
                   6146: 	}
1.194     albertel 6147: 
1.188     albertel 6148: 	$r->print(<<ENDSCRIPT);
                   6149: <script type="text/javascript">
                   6150: function change_radio(field) {
1.190     albertel 6151:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6152:     var i;
                   6153:     for (i=0;i<slct.length;i++) {
                   6154:         if (slct[i].value==field) { slct[i].checked=true; }
                   6155:     }
                   6156: }
                   6157: </script>
                   6158: ENDSCRIPT
1.187     albertel 6159: 	my $href="/adm/pickcode?".
1.359     www      6160: 	   "form=".&escape("scantronupload").
                   6161: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6162: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6163: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6164: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6165: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6166: 	    $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')\" />");
                   6167: 	    $r->print("\n<br />");
                   6168: 	}
1.272     albertel 6169: 	$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 6170: 	$r->print("\n<br /><br />");
1.157     albertel 6171:     } elsif ($error eq 'doublebubble') {
                   6172: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6173: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6174: 		  join(',',@{$arg}).'" />');
1.242     albertel 6175: 	$r->print($message);
1.157     albertel 6176: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6177: 	foreach my $question (@{$arg}) {
                   6178: 	    my $selected=$$scan_record{"scantron.$question.answer"};
1.422     foxr     6179: 	    &scantron_bubble_selector($r,$scan_config,$question,
                   6180: 				      split('',$selected));
1.157     albertel 6181: 	}
                   6182:     } elsif ($error eq 'missingbubble') {
                   6183: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6184: 	$r->print($message);
1.157     albertel 6185: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6186: 	$r->print("Some questions have no scanned bubbles\n");
                   6187: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6188: 		  join(',',@{$arg}).'" />');
                   6189: 	foreach my $question (@{$arg}) {
                   6190: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   6191: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   6192: 	}
                   6193:     } else {
                   6194: 	$r->print("\n<ul>");
                   6195:     }
                   6196:     $r->print("\n</li></ul>");
                   6197: 
                   6198: }
1.423     albertel 6199: 
                   6200: =pod
                   6201: 
                   6202: =item scantron_bubble_selector
                   6203:   
                   6204:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6205:    possibly showing the existing the selected bubbles if known
1.423     albertel 6206: 
                   6207:  Arguments:
                   6208:     $r           - Apache request object
                   6209:     $scan_config - hash from &get_scantron_config()
                   6210:     $quest       - number of the bubble line to make a corrector for
                   6211:     $selected    - array of letters of previously selected bubbles
                   6212:     $lines       - if present, number of bubble lines to show
                   6213: 
                   6214: =cut
                   6215: 
1.157     albertel 6216: sub scantron_bubble_selector {
1.422     foxr     6217:     my ($r,$scan_config,$quest,@selected, $lines)=@_;
1.157     albertel 6218:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6219: 
                   6220:     my $scmode=$$scan_config{'Qon'};
                   6221:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6222: 
1.422     foxr     6223: 
                   6224:     if (!defined($lines)) {
                   6225: 	$lines = 1;
                   6226:     }
                   6227:     my $total_lines = $lines*2;
1.157     albertel 6228:     my @alphabet=('A'..'Z');
1.422     foxr     6229:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6230: 
                   6231:     for (my $l = 0; $l < $lines; $l++) {
                   6232: 	if ($l != 0) {
                   6233: 	    $r->print('<tr>');
                   6234: 	}
                   6235: 
                   6236: 	# FIXME:  This loop probably has to be considerably more clever for
                   6237: 	#  multiline bubbles: User can multibubble by having bubbles in
                   6238: 	#  several lines.  User can skip lines legitimately etc. etc.
                   6239: 
                   6240: 	for (my $i=0;$i<$max;$i++) {
                   6241: 	    $r->print("\n".'<td align="center">');
                   6242: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6243: 		$r->print('X'); 
                   6244: 		shift(@selected) ;
                   6245: 	    } else { 
                   6246: 		$r->print('&nbsp;'); 
                   6247: 	    }
                   6248: 	    $r->print('</td>');
                   6249: 	    
                   6250: 	}
                   6251: 
                   6252: 	if ($l == 0) {
                   6253: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6254: 
                   6255: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6256: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6257: 	
                   6258: 	}
                   6259: 
                   6260: 	$r->print('</tr><tr>');
                   6261: 
                   6262: 	# FIXME: This may have to be a bit more clever for
                   6263: 	#        multiline questions (different values e.g..).
                   6264: 
                   6265: 	for (my $i=0;$i<$max;$i++) {
                   6266: 	    $r->print("\n".
                   6267: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6268: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6269: 	}
                   6270: 	$r->print('</tr>');
                   6271: 
                   6272: 	    
1.157     albertel 6273:     }
1.422     foxr     6274:     $r->print('</table>');
1.157     albertel 6275: }
                   6276: 
1.423     albertel 6277: =pod
                   6278: 
                   6279: =item num_matches
                   6280: 
1.424     albertel 6281:    Counts the number of characters that are the same between the two arguments.
                   6282: 
                   6283:  Arguments:
                   6284:    $orig - CODE from the scanline
                   6285:    $code - CODE to match against
                   6286: 
                   6287:  Returns:
                   6288:    $count - integer count of the number of same characters between the
                   6289:             two arguments
                   6290: 
1.423     albertel 6291: =cut
                   6292: 
1.194     albertel 6293: sub num_matches {
                   6294:     my ($orig,$code) = @_;
                   6295:     my @code=split(//,$code);
                   6296:     my @orig=split(//,$orig);
                   6297:     my $same=0;
                   6298:     for (my $i=0;$i<scalar(@code);$i++) {
                   6299: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6300:     }
                   6301:     return $same;
                   6302: }
                   6303: 
1.423     albertel 6304: =pod
                   6305: 
                   6306: =item scantron_get_closely_matching_CODEs
                   6307: 
1.424     albertel 6308:    Cycles through all CODEs and finds the set that has the greatest
                   6309:    number of same characters as the provided CODE
                   6310: 
                   6311:  Arguments:
                   6312:    $allcodes - hash ref returned by &get_codes()
                   6313:    $CODE     - CODE from the current scanline
                   6314: 
                   6315:  Returns:
                   6316:    2 element list
                   6317:     - first elements is number of how closely matching the best fit is 
                   6318:       (5 means best set has 5 matching characters)
                   6319:     - second element is an arrary ref containing the set of valid CODEs
                   6320:       that best fit the passed in CODE
                   6321: 
1.423     albertel 6322: =cut
                   6323: 
1.194     albertel 6324: sub scantron_get_closely_matching_CODEs {
                   6325:     my ($allcodes,$CODE)=@_;
                   6326:     my @CODEs;
                   6327:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6328: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6329:     }
                   6330: 
                   6331:     return ($#CODEs,$CODEs[-1]);
                   6332: }
                   6333: 
1.423     albertel 6334: =pod
                   6335: 
                   6336: =item get_codes
                   6337: 
1.424     albertel 6338:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6339:    set of remembered CODEs.
                   6340: 
                   6341:  Arguments:
                   6342:   $old_name - name of the set of remembered CODEs
                   6343:   $cdom     - domain of the course
                   6344:   $cnum     - internal course name
                   6345: 
                   6346:  Returns:
                   6347:   %allcodes - keys are the valid CODEs, values are all 1
                   6348: 
1.423     albertel 6349: =cut
                   6350: 
1.194     albertel 6351: sub get_codes {
1.280     foxr     6352:     my ($old_name, $cdom, $cnum) = @_;
                   6353:     if (!$old_name) {
                   6354: 	$old_name=$env{'form.scantron_CODElist'};
                   6355:     }
                   6356:     if (!$cdom) {
                   6357: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6358:     }
                   6359:     if (!$cnum) {
                   6360: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6361:     }
1.278     albertel 6362:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6363: 				    $cdom,$cnum);
                   6364:     my %allcodes;
                   6365:     if ($result{"type\0$old_name"} eq 'number') {
                   6366: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6367:     } else {
                   6368: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6369:     }
1.194     albertel 6370:     return %allcodes;
                   6371: }
                   6372: 
1.423     albertel 6373: =pod
                   6374: 
                   6375: =item scantron_validate_CODE
                   6376: 
1.424     albertel 6377:    Validates all scanlines in the selected file to not have any
                   6378:    invalid or underspecified CODEs and that none of the codes are
                   6379:    duplicated if this was requested.
                   6380: 
1.423     albertel 6381: =cut
                   6382: 
1.157     albertel 6383: sub scantron_validate_CODE {
                   6384:     my ($r,$currentphase) = @_;
1.257     albertel 6385:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6386:     if ($scantron_config{'CODElocation'} &&
                   6387: 	$scantron_config{'CODEstart'} &&
                   6388: 	$scantron_config{'CODElength'}) {
1.257     albertel 6389: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6390: 	    &FIXME_blow_up()
                   6391: 	}
                   6392:     } else {
                   6393: 	return (0,$currentphase+1);
                   6394:     }
                   6395:     
                   6396:     my %usedCODEs;
                   6397: 
1.194     albertel 6398:     my %allcodes=&get_codes();
1.186     albertel 6399: 
                   6400:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6401:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6402: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6403: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6404: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6405: 						 $scan_data);
                   6406: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6407: 	my $error=0;
1.224     albertel 6408: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6409: 	    &scantron_get_correction($r,$i,$scan_record,
                   6410: 				     \%scantron_config,
                   6411: 				     $line,'incorrectCODE',\%allcodes);
                   6412: 	    return(1,$currentphase);
                   6413: 	}
1.221     albertel 6414: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6415: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6416: 	    &scantron_get_correction($r,$i,$scan_record,
                   6417: 				     \%scantron_config,
1.194     albertel 6418: 				     $line,'incorrectCODE',\%allcodes);
                   6419: 	    return(1,$currentphase);
1.186     albertel 6420: 	}
1.214     albertel 6421: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6422: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6423: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6424: 	    &scantron_get_correction($r,$i,$scan_record,
                   6425: 				     \%scantron_config,
1.194     albertel 6426: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6427: 	    return(1,$currentphase);
1.186     albertel 6428: 	}
1.194     albertel 6429: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6430:     }
1.157     albertel 6431:     return (0,$currentphase+1);
                   6432: }
                   6433: 
1.423     albertel 6434: =pod
                   6435: 
                   6436: =item scantron_validate_doublebubble
                   6437: 
1.424     albertel 6438:    Validates all scanlines in the selected file to not have any
                   6439:    bubble lines with multiple bubbles marked.
                   6440: 
1.423     albertel 6441: =cut
                   6442: 
1.157     albertel 6443: sub scantron_validate_doublebubble {
                   6444:     my ($r,$currentphase) = @_;
                   6445:     #get student info
                   6446:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6447:     my %idmap=&username_to_idmap($classlist);
                   6448: 
                   6449:     #get scantron line setup
1.257     albertel 6450:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6451:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6452:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6453: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6454: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6455: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6456: 						 $scan_data);
                   6457: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6458: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6459: 				 'doublebubble',
                   6460: 				 $$scan_record{'scantron.doubleerror'});
                   6461:     	return (1,$currentphase);
                   6462:     }
                   6463:     return (0,$currentphase+1);
                   6464: }
                   6465: 
1.423     albertel 6466: =pod
                   6467: 
                   6468: =item scantron_get_maxbubble
                   6469: 
1.424     albertel 6470:    Returns the maximum number of bubble lines that are expected to
                   6471:    occur. Does this by walking the selected sequence rendering the
                   6472:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6473:    for what the current value of the problem counter is.
                   6474: 
                   6475:    Caches the result to $env{'form.scantron_maxbubble'}
                   6476: 
1.423     albertel 6477: =cut
                   6478: 
1.330     albertel 6479: sub scantron_get_maxbubble {    
1.257     albertel 6480:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6481: 	$env{'form.scantron_maxbubble'}) {
                   6482: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6483:     }
1.330     albertel 6484: 
1.191     albertel 6485:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6486:     my (undef,undef,$sequence)=
1.257     albertel 6487: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6488: 
1.191     albertel 6489:     my $map=$navmap->getResourceByUrl($sequence);
                   6490:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6491: 
                   6492:     &Apache::lonxml::clear_problem_counter();
                   6493: 
1.191     albertel 6494:     foreach my $resource (@resources) {
1.330     albertel 6495: 	my $result=&Apache::lonnet::ssi($resource->src(),
                   6496: 					('symb' => $resource->symb()));
1.191     albertel 6497:     }
                   6498:     &Apache::lonnet::delenv('scantron\.');
1.330     albertel 6499:     $env{'form.scantron_maxbubble'} =
                   6500: 	&Apache::lonxml::get_problem_counter()-1;
                   6501: 
1.257     albertel 6502:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6503: }
                   6504: 
1.423     albertel 6505: =pod
                   6506: 
                   6507: =item scantron_validate_missingbubbles
                   6508: 
1.424     albertel 6509:    Validates all scanlines in the selected file to not have any
                   6510:    bubble lines with missing bubbles that haven't been verified as missing.
                   6511: 
1.423     albertel 6512: =cut
                   6513: 
1.157     albertel 6514: sub scantron_validate_missingbubbles {
                   6515:     my ($r,$currentphase) = @_;
                   6516:     #get student info
                   6517:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6518:     my %idmap=&username_to_idmap($classlist);
                   6519: 
                   6520:     #get scantron line setup
1.257     albertel 6521:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6522:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6523:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6524:     if (!$max_bubble) { $max_bubble=2**31; }
                   6525:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6526: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6527: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6528: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6529: 						 $scan_data);
                   6530: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6531: 	my @to_correct;
                   6532: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6533: 	    if ($missing > $max_bubble) { next; }
                   6534: 	    push(@to_correct,$missing);
                   6535: 	}
                   6536: 	if (@to_correct) {
                   6537: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6538: 				     $line,'missingbubble',\@to_correct);
                   6539: 	    return (1,$currentphase);
                   6540: 	}
                   6541: 
                   6542:     }
                   6543:     return (0,$currentphase+1);
                   6544: }
                   6545: 
1.423     albertel 6546: =pod
                   6547: 
                   6548: =item scantron_process_students
                   6549: 
                   6550:    Routine that does the actual grading of the bubble sheet information.
                   6551: 
                   6552:    The parsed scanline hash is added to %env 
                   6553: 
                   6554:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6555:    foreach resource , with the form data of
                   6556: 
                   6557: 	'submitted'     =>'scantron' 
                   6558: 	'grade_target'  =>'grade',
                   6559: 	'grade_username'=> username of student
                   6560: 	'grade_domain'  => domain of student
                   6561: 	'grade_courseid'=> of course
                   6562: 	'grade_symb'    => symb of resource to grade
                   6563: 
                   6564:     This triggers a grading pass. The problem grading code takes care
                   6565:     of converting the bubbled letter information (now in %env) into a
                   6566:     valid submission.
                   6567: 
                   6568: =cut
                   6569: 
1.82      albertel 6570: sub scantron_process_students {
1.75      albertel 6571:     my ($r) = @_;
1.257     albertel 6572:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6573:     my ($symb)=&get_symb($r);
1.81      albertel 6574:     if (!$symb) {return '';}
1.324     albertel 6575:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6576: 
1.257     albertel 6577:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6578:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6579:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6580:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6581:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6582:     my $map=$navmap->getResourceByUrl($sequence);
                   6583:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6584: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6585:     my $result= <<SCANTRONFORM;
1.81      albertel 6586: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6587:   <input type="hidden" name="command" value="scantron_configphase" />
                   6588:   $default_form_data
                   6589: SCANTRONFORM
1.82      albertel 6590:     $r->print($result);
                   6591: 
                   6592:     my @delayqueue;
1.140     albertel 6593:     my %completedstudents;
                   6594:     
1.200     albertel 6595:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6596:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6597:  				    'Scantron Progress',$count,
1.195     albertel 6598: 				    'inline',undef,'scantronupload');
1.140     albertel 6599:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6600: 					  'Processing first student');
                   6601:     my $start=&Time::HiRes::time();
1.158     albertel 6602:     my $i=-1;
1.200     albertel 6603:     my ($uname,$udom,$started);
1.157     albertel 6604:     while ($i<$scanlines->{'count'}) {
                   6605:  	($uname,$udom)=('','');
                   6606:  	$i++;
1.200     albertel 6607:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6608:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 6609: 	if ($started) {
                   6610: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   6611: 						     'last student');
                   6612: 	}
                   6613: 	$started=1;
1.157     albertel 6614:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6615:  						 $scan_data);
                   6616:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   6617:  					      \%idmap,$i)) {
                   6618:   	    &scantron_add_delay(\@delayqueue,$line,
                   6619:  				'Unable to find a student that matches',1);
                   6620:  	    next;
                   6621:   	}
                   6622:  	if (exists $completedstudents{$uname}) {
                   6623:  	    &scantron_add_delay(\@delayqueue,$line,
                   6624:  				'Student '.$uname.' has multiple sheets',2);
                   6625:  	    next;
                   6626:  	}
                   6627:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 6628: 
                   6629: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 6630:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 6631: 
                   6632: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   6633: 	    &scantron_putfile($scanlines,$scan_data);
                   6634: 	}
1.161     albertel 6635: 	
                   6636: 	my $i=0;
1.83      albertel 6637: 	foreach my $resource (@resources) {
1.85      albertel 6638: 	    $i++;
1.193     albertel 6639: 	    my %form=('submitted'     =>'scantron',
                   6640: 		      'grade_target'  =>'grade',
                   6641: 		      'grade_username'=>$uname,
                   6642: 		      'grade_domain'  =>$udom,
1.257     albertel 6643: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 6644: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 6645: 	    if (exists($scan_record->{'scantron.CODE'})
                   6646: 		&& 
                   6647: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 6648: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 6649: 	    } else {
                   6650: 		$form{'CODE'}='';
1.193     albertel 6651: 	    }
                   6652: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 6653: 	    if ($result ne '') {
                   6654: 		&Apache::lonnet::logthis("scantron grading error -> $result");
1.257     albertel 6655: 		&Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
1.227     albertel 6656: 	    }
1.213     albertel 6657: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 6658: 	}
1.140     albertel 6659: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 6660: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 6661:     } continue {
1.330     albertel 6662: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 6663: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 6664:     }
1.140     albertel 6665:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 6666: #    my $lasttime = &Time::HiRes::time()-$start;
                   6667: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 6668: 
1.200     albertel 6669:     $r->print("</form>");
1.324     albertel 6670:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 6671:     return '';
1.75      albertel 6672: }
1.157     albertel 6673: 
1.423     albertel 6674: =pod
                   6675: 
                   6676: =item scantron_upload_scantron_data
                   6677: 
                   6678:     Creates the screen for adding a new bubble sheet data file to a course.
                   6679: 
                   6680: =cut
                   6681: 
1.157     albertel 6682: sub scantron_upload_scantron_data {
                   6683:     my ($r)=@_;
1.257     albertel 6684:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 6685:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 6686: 							  'domainid',
                   6687: 							  'coursename');
1.257     albertel 6688:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 6689: 						   'domainid');
1.324     albertel 6690:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 6691:     $r->print(<<UPLOAD);
                   6692: <script type="text/javascript" language="javascript">
                   6693:     function checkUpload(formname) {
                   6694: 	if (formname.upfile.value == "") {
                   6695: 	    alert("Please use the browse button to select a file from your local directory.");
                   6696: 	    return false;
                   6697: 	}
                   6698: 	formname.submit();
                   6699:     }
                   6700: </script>
                   6701: 
                   6702: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 6703: $default_form_data
1.181     albertel 6704: <table>
                   6705: <tr><td>$select_link </td></tr>
                   6706: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   6707: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   6708: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   6709: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   6710: </table>
1.157     albertel 6711: <input name='command' value='scantronupload_save' type='hidden' />
                   6712: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   6713: </form>
                   6714: UPLOAD
                   6715:     return '';
                   6716: }
                   6717: 
1.423     albertel 6718: =pod
                   6719: 
                   6720: =item scantron_upload_scantron_data_save
                   6721: 
                   6722:    Adds a provided bubble information data file to the course if user
                   6723:    has the correct privileges to do so.  
                   6724: 
                   6725: =cut
                   6726: 
1.157     albertel 6727: sub scantron_upload_scantron_data_save {
                   6728:     my($r)=@_;
1.324     albertel 6729:     my ($symb)=&get_symb($r,1);
1.182     albertel 6730:     my $doanotherupload=
                   6731: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   6732: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   6733: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   6734: 	'</form>'."\n";
1.257     albertel 6735:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 6736: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 6737: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 6738: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 6739: 	if ($symb) {
1.324     albertel 6740: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 6741: 	} else {
                   6742: 	    $r->print($doanotherupload);
                   6743: 	}
1.162     albertel 6744: 	return '';
                   6745:     }
1.257     albertel 6746:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       6747:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 6748:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 6749:     #FIXME
                   6750:     #copied from lonnet::userfileupload()
                   6751:     #make that function able to target a specified course
                   6752:     # Replace Windows backslashes by forward slashes
                   6753:     $fname=~s/\\/\//g;
                   6754:     # Get rid of everything but the actual filename
                   6755:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   6756:     # Replace spaces by underscores
                   6757:     $fname=~s/\s+/\_/g;
                   6758:     # Replace all other weird characters by nothing
                   6759:     $fname=~s/[^\w\.\-]//g;
                   6760:     # See if there is anything left
                   6761:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       6762:     my $uploadedfile=$fname;
1.157     albertel 6763:     $fname='scantron_orig_'.$fname;
1.257     albertel 6764:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 6765: 	$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 6766:     } else {
1.275     albertel 6767: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 6768: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 6769: 	    $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 6770: 	} else {
1.398     albertel 6771: 	    $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 6772: 	}
                   6773:     }
1.174     albertel 6774:     if ($symb) {
1.209     ng       6775: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 6776:     } else {
1.182     albertel 6777: 	$r->print($doanotherupload);
1.174     albertel 6778:     }
1.157     albertel 6779:     return '';
                   6780: }
                   6781: 
1.423     albertel 6782: =pod
                   6783: 
                   6784: =item valid_file
                   6785: 
1.424     albertel 6786:    Validates that the requested bubble data file exists in the course.
1.423     albertel 6787: 
                   6788: =cut
                   6789: 
1.202     albertel 6790: sub valid_file {
                   6791:     my ($requested_file)=@_;
                   6792:     foreach my $filename (sort(&scantron_filenames())) {
                   6793: 	if ($requested_file eq $filename) { return 1; }
                   6794:     }
                   6795:     return 0;
                   6796: }
                   6797: 
1.423     albertel 6798: =pod
                   6799: 
                   6800: =item scantron_download_scantron_data
                   6801: 
                   6802:    Shows a list of the three internal files (original, corrected,
                   6803:    skipped) for a specific bubble sheet data file that exists in the
                   6804:    course.
                   6805: 
                   6806: =cut
                   6807: 
1.202     albertel 6808: sub scantron_download_scantron_data {
                   6809:     my ($r)=@_;
1.324     albertel 6810:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 6811:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6812:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6813:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 6814:     if (! &valid_file($file)) {
                   6815: 	$r->print(<<ERROR);
                   6816: 	<p>
                   6817: 	    The requested file name was invalid.
                   6818:         </p>
                   6819: ERROR
1.324     albertel 6820: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 6821: 	return;
                   6822:     }
                   6823:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   6824:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   6825:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   6826:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   6827:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   6828:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   6829:     $r->print(<<DOWNLOAD);
                   6830:     <p>
                   6831: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   6832:     </p>
                   6833:     <p>
                   6834: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   6835:     </p>
                   6836:     <p>
                   6837: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   6838:     </p>
                   6839: DOWNLOAD
1.324     albertel 6840:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 6841:     return '';
                   6842: }
1.157     albertel 6843: 
1.423     albertel 6844: =pod
                   6845: 
                   6846: =back
                   6847: 
                   6848: =cut
                   6849: 
1.75      albertel 6850: #-------- end of section for handling grading scantron forms -------
                   6851: #
                   6852: #-------------------------------------------------------------------
                   6853: 
1.72      ng       6854: #-------------------------- Menu interface -------------------------
                   6855: #
                   6856: #--- Show a Grading Menu button - Calls the next routine ---
                   6857: sub show_grading_menu_form {
1.324     albertel 6858:     my ($symb)=@_;
1.125     ng       6859:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 6860: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 6861: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       6862: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   6863: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   6864: 	'</form>'."\n";
                   6865:     return $result;
                   6866: }
                   6867: 
1.77      ng       6868: # -- Retrieve choices for grading form
                   6869: sub savedState {
                   6870:     my %savedState = ();
1.257     albertel 6871:     if ($env{'form.saveState'}) {
                   6872: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       6873: 	    my ($key,$value) = split(/=/,$_,2);
                   6874: 	    $savedState{$key} = $value;
                   6875: 	}
                   6876:     }
                   6877:     return \%savedState;
                   6878: }
1.76      ng       6879: 
1.72      ng       6880: #--- Displays the main menu page -------
                   6881: sub gradingmenu {
                   6882:     my ($request) = @_;
1.324     albertel 6883:     my ($symb)=&get_symb($request);
1.72      ng       6884:     if (!$symb) {return '';}
1.76      ng       6885:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       6886: 
                   6887:     $request->print(<<GRADINGMENUJS);
                   6888: <script type="text/javascript" language="javascript">
1.116     ng       6889:     function checkChoice(formname,val,cmdx) {
                   6890: 	if (val <= 2) {
                   6891: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       6892: 	    var cmdsave = cmd;
1.116     ng       6893: 	} else {
                   6894: 	    cmd = cmdx;
1.118     ng       6895: 	    cmdsave = 'submission';
1.116     ng       6896: 	}
                   6897: 	formname.command.value = cmd;
1.118     ng       6898: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 6899: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       6900: 	if (val < 5) formname.submit();
                   6901: 	if (val == 5) {
1.72      ng       6902: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   6903: 	    formname.submit();
                   6904: 	}
1.238     albertel 6905: 	if (val < 7) formname.submit();
1.72      ng       6906:     }
                   6907: 
                   6908:     function checkReceiptNo(formname,nospace) {
                   6909: 	var receiptNo = formname.receipt.value;
                   6910: 	var checkOpt = false;
                   6911: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   6912: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   6913: 	if (checkOpt) {
                   6914: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   6915: 	    formname.receipt.value = "";
                   6916: 	    formname.receipt.focus();
                   6917: 	    return false;
                   6918: 	}
                   6919: 	return true;
                   6920:     }
                   6921: </script>
                   6922: GRADINGMENUJS
1.118     ng       6923:     &commonJSfunctions($request);
1.398     albertel 6924:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
1.324     albertel 6925:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       6926:     $result.=$table;
1.76      ng       6927:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       6928:     my $savedState = &savedState();
1.118     ng       6929:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       6930:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       6931:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       6932:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       6933: 
                   6934:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 6935: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       6936: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   6937: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       6938: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       6939: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       6940: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       6941: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   6942: 
1.326     albertel 6943:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   6944: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
1.72      ng       6945: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       6946: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   6947: 
1.326     albertel 6948:     $result.='<table width="100%" border="0">';
1.116     ng       6949:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.429     banghart 6950: 	'&nbsp;'.&mt('Select Section').': <select name="section" multiple="multiple" size="3">'."\n";
1.116     ng       6951:     if (ref($sections)) {
1.155     albertel 6952: 	foreach (sort (@$sections)) {
                   6953: 	    $result.='<option value="'.$_.'" '.
1.401     albertel 6954: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
1.155     albertel 6955: 	}
1.116     ng       6956:     }
1.401     albertel 6957:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.116     ng       6958: 
1.401     albertel 6959:     $result.=&mt('Student Status').':'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
1.72      ng       6960: 
1.116     ng       6961:     $result.='</td></tr>';
                   6962: 
1.288     albertel 6963:     $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
1.118     ng       6964: 	'<input type="radio" name="radioChoice" value="submission" '.
1.401     albertel 6965: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 6966: 	'</label> <select name="submitonly">'.
1.145     albertel 6967: 	'<option value="yes" '.
1.401     albertel 6968: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
1.301     albertel 6969: 	'<option value="queued" '.
1.401     albertel 6970: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
1.145     albertel 6971: 	'<option value="graded" '.
1.401     albertel 6972: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 6973: 	'<option value="incorrect" '.
1.401     albertel 6974: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 6975: 	'<option value="all" '.
1.401     albertel 6976: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       6977: 
1.116     ng       6978:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.288     albertel 6979: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.401     albertel 6980: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
1.288     albertel 6981: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       6982: 
1.118     ng       6983:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
1.288     albertel 6984: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.401     albertel 6985: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
1.288     albertel 6986: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       6987: 
1.116     ng       6988:     $result.='<tr bgcolor="#ffffe6"><td><br />'.
1.126     ng       6989: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       6990: 	'</td></tr></table>'."\n";
                   6991: 
                   6992:     $result.='</td><td valign="top">';
                   6993: 
1.326     albertel 6994:     $result.='<table width="100%" border="0">';
1.116     ng       6995:     $result.='<tr bgcolor="#ffffe6"><td>'.
1.184     www      6996: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   6997: 	' '.&mt('scores from file').' </td></tr>'."\n";
1.72      ng       6998: 
1.404     www      6999:     $result.='<tr bgcolor="#ffffe6"><td>'.
                   7000:         '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
                   7001:         ' '.&mt('clicker file').' </td></tr>'."\n";
1.400     www      7002: 
1.75      albertel 7003:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.116     ng       7004: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
1.184     www      7005: 	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
1.75      albertel 7006: 
1.257     albertel 7007:     if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
1.72      ng       7008: 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.184     www      7009: 	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   7010: 	    ' '.&mt('receipt').': '.
1.257     albertel 7011: 	    &Apache::lonnet::recprefix($env{'request.course.id'}).
1.326     albertel 7012: 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
1.72      ng       7013: 	    '</td></tr>'."\n";
                   7014:     } 
1.238     albertel 7015:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7016: 	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   7017: 	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
1.279     albertel 7018:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7019: 	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   7020: 	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
1.44      ng       7021: 
1.401     albertel 7022:     $result.='</table>'."\n".
1.72      ng       7023: 	'</td></tr></table>'."\n".
1.401     albertel 7024: 	'</td></tr></table></form>'."\n";
1.44      ng       7025:     return $result;
1.2       albertel 7026: }
                   7027: 
1.285     albertel 7028: sub reset_perm {
                   7029:     undef(%perm);
                   7030: }
                   7031: 
                   7032: sub init_perm {
                   7033:     &reset_perm();
1.300     albertel 7034:     foreach my $test_perm ('vgr','mgr','opa') {
                   7035: 
                   7036: 	my $scope = $env{'request.course.id'};
                   7037: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7038: 
                   7039: 	    $scope .= '/'.$env{'request.course.sec'};
                   7040: 	    if ( $perm{$test_perm}=
                   7041: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7042: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7043: 	    } else {
                   7044: 		delete($perm{$test_perm});
                   7045: 	    }
1.285     albertel 7046: 	}
                   7047:     }
                   7048: }
                   7049: 
1.400     www      7050: sub gather_clicker_ids {
1.408     albertel 7051:     my %clicker_ids;
1.400     www      7052: 
                   7053:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7054: 
                   7055:     # Set up a couple variables.
1.407     albertel 7056:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7057:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.400     www      7058: 
1.407     albertel 7059:     foreach my $student (keys(%$classlist)) {
1.400     www      7060: 
1.407     albertel 7061:         my $username = $classlist->{$student}->[$username_idx];
                   7062:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7063:         my $clickers =
1.408     albertel 7064: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7065:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7066:             $id=~s/^[\#0]+//;
1.421     www      7067:             $id=~s/[\-\:]//g;
1.407     albertel 7068:             if (exists($clicker_ids{$id})) {
1.408     albertel 7069: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7070:             } else {
1.408     albertel 7071: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7072:             }
                   7073:         }
                   7074:     }
1.407     albertel 7075:     return %clicker_ids;
1.400     www      7076: }
                   7077: 
1.402     www      7078: sub gather_adv_clicker_ids {
1.408     albertel 7079:     my %clicker_ids;
1.402     www      7080:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7081:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7082:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7083:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7084:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7085:             my ($puname,$pudom)=split(/\:/,$person);
                   7086:             my $clickers =
1.408     albertel 7087: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7088:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7089: 		$id=~s/^[\#0]+//;
1.421     www      7090:                 $id=~s/[\-\:]//g;
1.408     albertel 7091: 		if (exists($clicker_ids{$id})) {
                   7092: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7093: 		} else {
                   7094: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7095: 		}
1.405     www      7096:             }
1.402     www      7097:         }
                   7098:     }
1.407     albertel 7099:     return %clicker_ids;
1.402     www      7100: }
                   7101: 
1.413     www      7102: sub clicker_grading_parameters {
                   7103:     return ('gradingmechanism' => 'scalar',
                   7104:             'upfiletype' => 'scalar',
                   7105:             'specificid' => 'scalar',
                   7106:             'pcorrect' => 'scalar',
                   7107:             'pincorrect' => 'scalar');
                   7108: }
                   7109: 
1.400     www      7110: sub process_clicker {
                   7111:     my ($r)=@_;
                   7112:     my ($symb)=&get_symb($r);
                   7113:     if (!$symb) {return '';}
                   7114:     my $result=&checkforfile_js();
                   7115:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7116:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7117:     $result.=$table;
                   7118:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7119:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7120:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7121:         '.</b></td></tr>'."\n";
                   7122:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7123: # Attempt to restore parameters from last session, set defaults if not present
                   7124:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7125:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7126:                                                  \%Saveable_Parameters);
                   7127:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7128:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7129:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7130:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7131: 
                   7132:     my %checked;
                   7133:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7134:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7135:           $checked{$gradingmechanism}="checked='checked'";
                   7136:        }
                   7137:     }
                   7138: 
1.400     www      7139:     my $upload=&mt("Upload File");
                   7140:     my $type=&mt("Type");
1.402     www      7141:     my $attendance=&mt("Award points just for participation");
                   7142:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7143:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7144:     my $pcorrect=&mt("Percentage points for correct solution");
                   7145:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7146:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7147: 						   ('iclicker' => 'i>clicker',
                   7148:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7149:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7150:     $result.=<<ENDUPFORM;
1.402     www      7151: <script type="text/javascript">
                   7152: function sanitycheck() {
                   7153: // Accept only integer percentages
                   7154:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7155:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7156: // Find out grading choice
                   7157:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7158:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7159:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7160:       }
                   7161:    }
                   7162: // By default, new choice equals user selection
                   7163:    newgradingchoice=gradingchoice;
                   7164: // Not good to give more points for false answers than correct ones
                   7165:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7166:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7167:    }
                   7168: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7169:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7170:       document.forms.gradesupload.pcorrect.value=100;
                   7171:       document.forms.gradesupload.pincorrect.value=100;
                   7172:    }
                   7173: // If the values are different, cannot be attendance only
                   7174:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7175:        (gradingchoice=='attendance')) {
                   7176:        newgradingchoice='personnel';
                   7177:    }
                   7178: // Change grading choice to new one
                   7179:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7180:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7181:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7182:       } else {
                   7183:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7184:       }
                   7185:    }
                   7186: // Remember the old state
                   7187:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7188: }
                   7189: </script>
1.400     www      7190: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7191: <input type="hidden" name="symb" value="$symb" />
                   7192: <input type="hidden" name="command" value="processclickerfile" />
                   7193: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7194: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7195: <input type="file" name="upfile" size="50" />
                   7196: <br /><label>$type: $selectform</label>
1.413     www      7197: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
                   7198: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
                   7199: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
1.414     www      7200: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7201: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7202: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7203: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7204: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7205: </form>
                   7206: ENDUPFORM
                   7207:     $result.='</td></tr></table>'."\n".
                   7208:              '</td></tr></table><br /><br />'."\n";
                   7209:     $result.=&show_grading_menu_form($symb);
                   7210:     return $result;
                   7211: }
                   7212: 
                   7213: sub process_clicker_file {
                   7214:     my ($r)=@_;
                   7215:     my ($symb)=&get_symb($r);
                   7216:     if (!$symb) {return '';}
1.413     www      7217: 
                   7218:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7219:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7220:                                               \%Saveable_Parameters);
                   7221: 
1.400     www      7222:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7223:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7224: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7225: 	return $result.&show_grading_menu_form($symb);
1.404     www      7226:     }
1.407     albertel 7227:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7228:     my %correct_ids;
1.404     www      7229:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7230: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7231:     }
                   7232:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7233: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7234: 	   $correct_id=~tr/a-z/A-Z/;
                   7235: 	   $correct_id=~s/\s//gs;
                   7236: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7237:            $correct_id=~s/[\-\:]//g;
1.414     www      7238:            if ($correct_id) {
                   7239: 	      $correct_ids{$correct_id}='specified';
                   7240:            }
                   7241:         }
1.400     www      7242:     }
1.404     www      7243:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7244: 	$result.=&mt('Score based on attendance only');
1.404     www      7245:     } else {
1.408     albertel 7246: 	my $number=0;
1.411     www      7247: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7248: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7249: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7250: 	    if ($correct_ids{$id} eq 'specified') {
                   7251: 		$result.=&mt('specified');
                   7252: 	    } else {
                   7253: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7254: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7255: 	    }
                   7256: 	    $number++;
                   7257: 	}
1.411     www      7258:         $result.="</p>\n";
1.408     albertel 7259: 	if ($number==0) {
                   7260: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7261: 	    return $result.&show_grading_menu_form($symb);
                   7262: 	}
1.404     www      7263:     }
1.405     www      7264:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7265:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7266: 		     '<span class="LC_error">',
                   7267: 		     '</span>',
                   7268: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7269:         return $result.&show_grading_menu_form($symb);
                   7270:     }
1.410     www      7271: 
                   7272: # Were able to get all the info needed, now analyze the file
                   7273: 
1.411     www      7274:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7275:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7276:     my $heading=&mt('Scanning clicker file');
                   7277:     $result.=(<<ENDHEADER);
                   7278: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7279: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7280: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7281: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7282: <input type="hidden" name="symb" value="$symb" />
                   7283: <input type="hidden" name="command" value="assignclickergrades" />
                   7284: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7285: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7286: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7287: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7288: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7289: ENDHEADER
1.408     albertel 7290:     my %responses;
                   7291:     my @questiontitles;
1.405     www      7292:     my $errormsg='';
                   7293:     my $number=0;
                   7294:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7295: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7296:     }
1.419     www      7297:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7298:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7299:     }
1.411     www      7300:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7301:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   7302:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7303:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7304:              '<br />';
1.414     www      7305: # Remember Question Titles
                   7306: # FIXME: Possibly need delimiter other than ":"
                   7307:     for (my $i=0;$i<$number;$i++) {
                   7308:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7309:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7310:     }
1.411     www      7311:     my $correct_count=0;
                   7312:     my $student_count=0;
                   7313:     my $unknown_count=0;
1.414     www      7314: # Match answers with usernames
                   7315: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7316:     foreach my $id (keys(%responses)) {
1.410     www      7317:        if ($correct_ids{$id}) {
1.414     www      7318:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7319:           $correct_count++;
1.410     www      7320:        } elsif ($clicker_ids{$id}) {
                   7321:           $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7322:           $student_count++;
1.410     www      7323:        } else {
1.411     www      7324:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7325:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7326:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7327:                    "\n".&mt("Domain").": ".
                   7328:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7329:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7330:           $unknown_count++;
1.410     www      7331:        }
1.405     www      7332:     }
1.412     www      7333:     $result.='<hr />'.
                   7334:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7335:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7336:        if ($correct_count==0) {
                   7337:           $errormsg.="Found no correct answers answers for grading!";
                   7338:        } elsif ($correct_count>1) {
1.414     www      7339:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7340:        }
                   7341:     }
1.428     www      7342:     if ($number<1) {
                   7343:        $errormsg.="Found no questions.";
                   7344:     }
1.412     www      7345:     if ($errormsg) {
                   7346:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7347:     } else {
                   7348:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7349:     }
                   7350:     $result.='</form></td></tr></table>'."\n".
1.410     www      7351:              '</td></tr></table><br /><br />'."\n";
1.404     www      7352:     return $result.&show_grading_menu_form($symb);
1.400     www      7353: }
                   7354: 
1.405     www      7355: sub iclicker_eval {
1.406     www      7356:     my ($questiontitles,$responses)=@_;
1.405     www      7357:     my $number=0;
                   7358:     my $errormsg='';
                   7359:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7360:         my %components=&Apache::loncommon::record_sep($line);
                   7361:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7362: 	if ($entries[0] eq 'Question') {
                   7363: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7364: 		$$questiontitles[$number]=$entries[$i];
                   7365: 		$number++;
                   7366: 	    }
                   7367: 	}
                   7368: 	if ($entries[0]=~/^\#/) {
                   7369: 	    my $id=$entries[0];
                   7370: 	    my @idresponses;
                   7371: 	    $id=~s/^[\#0]+//;
                   7372: 	    for (my $i=0;$i<$number;$i++) {
                   7373: 		my $idx=3+$i*6;
                   7374: 		push(@idresponses,$entries[$idx]);
                   7375: 	    }
                   7376: 	    $$responses{$id}=join(',',@idresponses);
                   7377: 	}
1.405     www      7378:     }
                   7379:     return ($errormsg,$number);
                   7380: }
                   7381: 
1.419     www      7382: sub interwrite_eval {
                   7383:     my ($questiontitles,$responses)=@_;
                   7384:     my $number=0;
                   7385:     my $errormsg='';
1.420     www      7386:     my $skipline=1;
                   7387:     my $questionnumber=0;
                   7388:     my %idresponses=();
1.419     www      7389:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   7390:         my %components=&Apache::loncommon::record_sep($line);
                   7391:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      7392:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   7393:         if ($entries[1] eq 'Response') { $skipline=1; }
                   7394:         next if $skipline;
                   7395:         if ($entries[0]!=$questionnumber) {
                   7396:            $questionnumber=$entries[0];
                   7397:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   7398:            $number++;
1.419     www      7399:         }
1.420     www      7400:         my $id=$entries[4];
                   7401:         $id=~s/^[\#0]+//;
1.421     www      7402:         $id=~s/^v\d*\://i;
                   7403:         $id=~s/[\-\:]//g;
1.420     www      7404:         $idresponses{$id}[$number]=$entries[6];
                   7405:     }
                   7406:     foreach my $id (keys %idresponses) {
                   7407:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   7408:        $$responses{$id}=~s/^\s*\,//;
1.419     www      7409:     }
                   7410:     return ($errormsg,$number);
                   7411: }
                   7412: 
1.414     www      7413: sub assign_clicker_grades {
                   7414:     my ($r)=@_;
                   7415:     my ($symb)=&get_symb($r);
                   7416:     if (!$symb) {return '';}
1.416     www      7417: # See which part we are saving to
                   7418:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   7419: # FIXME: This should probably look for the first handgradeable part
                   7420:     my $part=$$partlist[0];
                   7421: # Start screen output
1.414     www      7422:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      7423: 
1.414     www      7424:     my $heading=&mt('Assigning grades based on clicker file');
                   7425:     $result.=(<<ENDHEADER);
                   7426: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7427: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7428: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7429: ENDHEADER
                   7430: # Get correct result
                   7431: # FIXME: Possibly need delimiter other than ":"
                   7432:     my @correct=();
1.415     www      7433:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   7434:     my $number=$env{'form.number'};
                   7435:     if ($gradingmechanism ne 'attendance') {
1.414     www      7436:        foreach my $key (keys(%env)) {
                   7437:           if ($key=~/^form\.correct\:/) {
                   7438:              my @input=split(/\,/,$env{$key});
                   7439:              for (my $i=0;$i<=$#input;$i++) {
                   7440:                  if (($correct[$i]) && ($input[$i]) &&
                   7441:                      ($correct[$i] ne $input[$i])) {
                   7442:                     $result.='<br /><span class="LC_warning">'.
                   7443:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   7444:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   7445:                  } elsif ($input[$i]) {
                   7446:                     $correct[$i]=$input[$i];
                   7447:                  }
                   7448:              }
                   7449:           }
                   7450:        }
1.415     www      7451:        for (my $i=0;$i<$number;$i++) {
1.414     www      7452:           if (!$correct[$i]) {
                   7453:              $result.='<br /><span class="LC_error">'.
                   7454:                       &mt('No correct result given for question "[_1]"!',
                   7455:                           $env{'form.question:'.$i}).'</span>';
                   7456:           }
                   7457:        }
                   7458:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   7459:     }
                   7460: # Start grading
1.415     www      7461:     my $pcorrect=$env{'form.pcorrect'};
                   7462:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      7463:     my $storecount=0;
1.415     www      7464:     foreach my $key (keys(%env)) {
1.420     www      7465:        my $user='';
1.415     www      7466:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      7467:           $user=$1;
                   7468:        }
                   7469:        if ($key=~/^form\.unknown\:(.*)$/) {
                   7470:           my $id=$1;
                   7471:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   7472:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
                   7473:           }
                   7474:        }
                   7475:        if ($user) { 
1.415     www      7476:           my @answer=split(/\,/,$env{$key});
                   7477:           my $sum=0;
                   7478:           for (my $i=0;$i<$number;$i++) {
                   7479:              if ($answer[$i]) {
                   7480:                 if ($gradingmechanism eq 'attendance') {
                   7481:                    $sum+=$pcorrect;
                   7482:                 } else {
                   7483:                    if ($answer[$i] eq $correct[$i]) {
                   7484:                       $sum+=$pcorrect;
                   7485:                    } else {
                   7486:                       $sum+=$pincorrect;
                   7487:                    }
                   7488:                 }
                   7489:              }
                   7490:           }
1.416     www      7491:           my $ave=$sum/(100*$number);
                   7492: # Store
                   7493:           my ($username,$domain)=split(/\:/,$user);
                   7494:           my %grades=();
                   7495:           $grades{"resource.$part.solved"}='correct_by_override';
                   7496:           $grades{"resource.$part.awarded"}=$ave;
                   7497:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   7498:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   7499:                                                  $env{'request.course.id'},
                   7500:                                                  $domain,$username);
                   7501:           if ($returncode ne 'ok') {
                   7502:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   7503:           } else {
                   7504:              $storecount++;
                   7505:           }
1.415     www      7506:        }
                   7507:     }
                   7508: # We are done
1.416     www      7509:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   7510:              '</td></tr></table>'."\n".
1.414     www      7511:              '</td></tr></table><br /><br />'."\n";
                   7512:     return $result.&show_grading_menu_form($symb);
                   7513: }
                   7514: 
1.1       albertel 7515: sub handler {
1.41      ng       7516:     my $request=$_[0];
1.102     albertel 7517: 
1.285     albertel 7518:     &reset_perm();
1.257     albertel 7519:     if ($env{'browser.mathml'}) {
1.141     www      7520: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       7521:     } else {
1.141     www      7522: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       7523:     }
                   7524:     $request->send_http_header;
1.44      ng       7525:     return '' if $request->header_only;
1.41      ng       7526:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 7527:     my $symb=&get_symb($request,1);
1.160     albertel 7528:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   7529:     my $command=$commands[0];
                   7530:     if ($#commands > 0) {
                   7531: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   7532:     }
1.353     albertel 7533:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 7534:     if ($symb eq '' && $command eq '') {
1.257     albertel 7535: 	if ($env{'user.adv'}) {
                   7536: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   7537: 		($env{'form.codethree'})) {
                   7538: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   7539: 		    $env{'form.codethree'};
1.41      ng       7540: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   7541: 		    &Apache::lonnet::checkin($token);
                   7542: 		if ($tsymb) {
1.137     albertel 7543: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       7544: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 7545: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   7546: 					  ('grade_username' => $tuname,
                   7547: 					   'grade_domain' => $tudom,
                   7548: 					   'grade_courseid' => $tcrsid,
                   7549: 					   'grade_symb' => $tsymb)));
1.41      ng       7550: 		    } else {
1.45      ng       7551: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 7552: 		    }
1.41      ng       7553: 		} else {
1.45      ng       7554: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       7555: 		}
1.14      www      7556: 	    } else {
1.41      ng       7557: 		$request->print(&Apache::lonxml::tokeninputfield());
                   7558: 	    }
                   7559: 	}
                   7560:     } else {
1.285     albertel 7561: 	&init_perm();
1.104     albertel 7562: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 7563: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 7564: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       7565: 	    &pickStudentPage($request);
1.103     albertel 7566: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       7567: 	    &displayPage($request);
1.104     albertel 7568: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       7569: 	    &updateGradeByPage($request);
1.104     albertel 7570: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       7571: 	    &processGroup($request);
1.104     albertel 7572: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.41      ng       7573: 	    $request->print(&gradingmenu($request));
1.104     albertel 7574: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       7575: 	    $request->print(&viewgrades($request));
1.104     albertel 7576: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       7577: 	    $request->print(&processHandGrade($request));
1.106     albertel 7578: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       7579: 	    $request->print(&editgrades($request));
1.106     albertel 7580: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       7581: 	    $request->print(&verifyreceipt($request));
1.400     www      7582:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   7583:             $request->print(&process_clicker($request));
                   7584:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   7585:             $request->print(&process_clicker_file($request));
1.414     www      7586:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   7587:             $request->print(&assign_clicker_grades($request));
1.106     albertel 7588: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       7589: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 7590: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       7591: 	    $request->print(&csvupload($request));
1.106     albertel 7592: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       7593: 	    $request->print(&csvuploadmap($request));
1.246     albertel 7594: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 7595: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 7596: 		$request->print(&csvuploadoptions($request));
1.41      ng       7597: 	    } else {
1.257     albertel 7598: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   7599: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       7600: 		} else {
1.257     albertel 7601: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       7602: 		}
                   7603: 		$request->print(&csvuploadmap($request));
                   7604: 	    }
1.246     albertel 7605: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   7606: 	    $request->print(&csvuploadassign($request));
1.106     albertel 7607: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 7608: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 7609:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   7610:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 7611: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   7612: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 7613: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 7614: 	    $request->print(&scantron_process_students($request));
1.157     albertel 7615:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 7616:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   7617: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 7618:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 7619:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 7620:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   7621: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 7622:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 7623:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 7624: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 7625:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 7626: 	} elsif ($command) {
1.157     albertel 7627: 	    $request->print("Access Denied ($command)");
1.26      albertel 7628: 	}
1.2       albertel 7629:     }
1.353     albertel 7630:     $request->print(&Apache::loncommon::end_page());
1.44      ng       7631:     return '';
                   7632: }
                   7633: 
1.1       albertel 7634: 1;
                   7635: 
1.13      albertel 7636: __END__;

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