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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.400   ! www         4: # $Id: grades.pm,v 1.399 2007/05/10 16:06:09 albertel Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: package Apache::grades;
                     30: use strict;
                     31: use Apache::style;
                     32: use Apache::lonxml;
                     33: use Apache::lonnet;
1.3       albertel   34: use Apache::loncommon;
1.112     ng         35: use Apache::lonhtmlcommon;
1.68      ng         36: use Apache::lonnavmaps;
1.1       albertel   37: use Apache::lonhomework;
1.55      matthew    38: use Apache::loncoursedata;
1.362     albertel   39: use Apache::lonmsg();
1.1       albertel   40: use Apache::Constants qw(:common);
1.167     sakharuk   41: use Apache::lonlocal;
1.386     raeburn    42: use Apache::lonenc;
1.170     albertel   43: use String::Similarity;
1.359     www        44: use lib '/home/httpd/lib/perl';
                     45: use LONCAPA;
                     46: 
1.315     bowersj2   47: use POSIX qw(floor);
1.87      www        48: 
                     49: my %oldessays=();
1.103     albertel   50: my %perm=();
1.1       albertel   51: 
1.68      ng         52: # ----- These first few routines are general use routines.----
1.44      ng         53: #
1.146     albertel   54: # --- Retrieve the parts from the metadata file.---
1.44      ng         55: sub getpartlist {
1.324     albertel   56:     my ($symb) = @_;
                     57:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.146     albertel   58:     my $partorder = &Apache::lonnet::metadata($url, 'partorder');
                     59:     my @parts;
                     60:     if ($partorder) {
                     61: 	for my $part (split (/,/,$partorder)) {
                     62: 	    if (!&Apache::loncommon::check_if_partid_hidden($part,$symb)) {
                     63: 		push(@parts, $part);
                     64: 	    }
                     65: 	}	    
                     66:     } else {
                     67: 	my $metadata = &Apache::lonnet::metadata($url, 'packages');
                     68: 	foreach (split(/\,/,$metadata)) {
                     69: 	    if ($_ =~ /^part_(.*)$/) {
                     70: 		if (!&Apache::loncommon::check_if_partid_hidden($1,$symb)) {
                     71: 		    push(@parts, $1);
                     72: 		}
                     73: 	    }
1.41      ng         74: 	}
1.16      albertel   75:     }
1.146     albertel   76:     my @stores;
                     77:     foreach my $part (@parts) {
                     78: 	my (@metakeys) = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                     79: 	foreach my $key (@metakeys) {
                     80: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                     81: 	}
                     82:     }
                     83:     return @stores;
1.2       albertel   84: }
                     85: 
1.44      ng         86: # --- Get the symbolic name of a problem and the url
1.324     albertel   87: sub get_symb {
1.173     albertel   88:     my ($request,$silent) = @_;
1.257     albertel   89:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                     90:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel   91:     if ($symb eq '') { 
                     92: 	if (!$silent) {
                     93: 	    $request->print("Unable to handle ambiguous references:$url:.");
                     94: 	    return ();
                     95: 	}
                     96:     }
1.324     albertel   97:     return ($symb);
1.32      ng         98: }
                     99: 
1.129     ng        100: #--- Format fullname, username:domain if different for display
                    101: #--- Use anywhere where the student names are listed
                    102: sub nameUserString {
                    103:     my ($type,$fullname,$uname,$udom) = @_;
                    104:     if ($type eq 'header') {
1.398     albertel  105: 	return '<b>&nbsp;Fullname&nbsp;</b><span class="LC_internal_info">(Username)</span>';
1.129     ng        106:     } else {
1.398     albertel  107: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    108: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        109:     }
                    110: }
                    111: 
1.44      ng        112: #--- Get the partlist and the response type for a given problem. ---
                    113: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        114: sub response_type {
1.324     albertel  115:     my ($symb) = shift;
1.377     albertel  116: 
                    117:     my $navmap = Apache::lonnavmaps::navmap->new();
                    118:     my $res = $navmap->getBySymb($symb);
                    119:     my $partlist = $res->parts();
1.392     albertel  120:     my %vPart = 
                    121: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  122:     my (%response_types,%handgrade);
                    123:     foreach my $part (@{ $partlist }) {
1.392     albertel  124: 	next if (%vPart && !exists($vPart{$part}));
                    125: 
1.377     albertel  126: 	my @types = $res->responseType($part);
                    127: 	my @ids = $res->responseIds($part);
                    128: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    129: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    130: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    131: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    132: 				     '.handgrade',$symb);
1.41      ng        133: 	}
                    134:     }
1.377     albertel  135:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        136: }
                    137: 
1.375     albertel  138: sub flatten_responseType {
                    139:     my ($responseType) = @_;
                    140:     my @part_response_id =
                    141: 	map { 
                    142: 	    my $part = $_;
                    143: 	    map {
                    144: 		[$part,$_]
                    145: 		} sort(keys(%{ $responseType->{$part} }));
                    146: 	} sort(keys(%$responseType));
                    147:     return @part_response_id;
                    148: }
                    149: 
1.207     albertel  150: sub get_display_part {
1.324     albertel  151:     my ($partID,$symb)=@_;
1.207     albertel  152:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    153:     if (defined($display) and $display ne '') {
1.398     albertel  154: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  155:     } else {
                    156: 	$display=$partID;
                    157:     }
                    158:     return $display;
                    159: }
1.269     raeburn   160: 
1.118     ng        161: #--- Show resource title
                    162: #--- and parts and response type
                    163: sub showResourceInfo {
1.324     albertel  164:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  165:     my $col=3;
                    166:     if ($checkboxes) { $col=4; }
1.398     albertel  167:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    168:     $result .='<table border="0">';
1.324     albertel  169:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        170:     my %resptype = ();
1.122     ng        171:     my $hdgrade='no';
1.154     albertel  172:     my %partsseen;
1.375     albertel  173:     foreach my $partID (sort keys(%$responseType)) {
                    174: 	foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
                    175: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    176: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    177: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    178: 	    $result.='<tr>';
                    179: 	    if ($checkboxes) {
                    180: 		if (exists($partsseen{$partID})) {
                    181: 		    $result.="<td>&nbsp;</td>";
                    182: 		} else {
                    183: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='on' /></td>";
                    184: 		}
                    185: 		$partsseen{$partID}=1;
1.154     albertel  186: 	    }
1.375     albertel  187: 	    my $display_part=&get_display_part($partID,$symb);
1.398     albertel  188: 	    $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
                    189: 		$resID.'</span></td>'.
1.375     albertel  190: 		'<td><b>Type: </b>'.$responsetype.'</td></tr>';
                    191: #	    '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
1.154     albertel  192: 	}
1.118     ng        193:     }
                    194:     $result.='</table>'."\n";
1.147     albertel  195:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        196: }
                    197: 
1.148     albertel  198: 
                    199: sub get_order {
                    200:     my ($partid,$respid,$symb,$uname,$udom)=@_;
                    201:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    202:     $url=&Apache::lonnet::clutter($url);
                    203:     my $subresult=&Apache::lonnet::ssi($url,
                    204: 				       ('grade_target' => 'analyze'),
                    205: 				       ('grade_domain' => $udom),
                    206: 				       ('grade_symb' => $symb),
                    207: 				       ('grade_courseid' => 
1.257     albertel  208: 					        $env{'request.course.id'}),
1.148     albertel  209: 				       ('grade_username' => $uname));
1.149     albertel  210:     (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
1.148     albertel  211:     my %analyze=&Apache::lonnet::str2hash($subresult);
                    212:     return ($analyze{"$partid.$respid.shown"});
                    213: }
1.118     ng        214: #--- Clean response type for display
1.335     albertel  215: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    216: #        response types only.
1.118     ng        217: sub cleanRecord {
1.336     albertel  218:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    219: 	$uname,$udom) = @_;
1.398     albertel  220:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  221:     if ($response =~ /^(option|rank)$/) {
                    222: 	my %answer=&Apache::lonnet::str2hash($answer);
                    223: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    224: 	my ($toprow,$bottomrow);
                    225: 	foreach my $foil (@$order) {
                    226: 	    if ($grading{$foil} == 1) {
                    227: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    228: 	    } else {
                    229: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    230: 	    }
1.398     albertel  231: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  232: 	}
                    233: 	return '<blockquote><table border="1">'.
                    234: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  235: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  236: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    237:     } elsif ($response eq 'match') {
                    238: 	my %answer=&Apache::lonnet::str2hash($answer);
                    239: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    240: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    241: 	my ($toprow,$middlerow,$bottomrow);
                    242: 	foreach my $foil (@$order) {
                    243: 	    my $item=shift(@items);
                    244: 	    if ($grading{$foil} == 1) {
                    245: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  246: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  247: 	    } else {
                    248: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  249: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  250: 	    }
1.398     albertel  251: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        252: 	}
1.126     ng        253: 	return '<blockquote><table border="1">'.
1.148     albertel  254: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  255: 	    '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
1.148     albertel  256: 	    $middlerow.'</tr>'.
1.398     albertel  257: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  258: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    259:     } elsif ($response eq 'radiobutton') {
                    260: 	my %answer=&Apache::lonnet::str2hash($answer);
                    261: 	my ($toprow,$bottomrow);
                    262: 	my $correct=($order->[0])+1;
                    263: 	for (my $i=1;$i<=$#$order;$i++) {
                    264: 	    my $foil=$order->[$i];
                    265: 	    if (exists($answer{$foil})) {
                    266: 		if ($i == $correct) {
                    267: 		    $toprow.='<td><b>true</b></td>';
                    268: 		} else {
                    269: 		    $toprow.='<td><i>true</i></td>';
                    270: 		}
                    271: 	    } else {
                    272: 		$toprow.='<td>false</td>';
                    273: 	    }
1.398     albertel  274: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  275: 	}
                    276: 	return '<blockquote><table border="1">'.
                    277: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  278: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  279: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    280:     } elsif ($response eq 'essay') {
1.257     albertel  281: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        282: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  283: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    284: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        285: 
1.257     albertel  286: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    287: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    288: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    289: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    290: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    291: 	    $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        292: 	}
1.166     albertel  293: 	$answer =~ s-\n-<br />-g;
                    294: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  295:     } elsif ( $response eq 'organic') {
                    296: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    297: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    298: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    299: 	return $result;
1.335     albertel  300:     } elsif ( $response eq 'Task') {
                    301: 	if ( $answer eq 'SUBMITTED') {
                    302: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  303: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  304: 	    return $result;
                    305: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    306: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    307: 			       keys(%{$record}));
                    308: 	    return join('<br />',($version,@matches));
                    309: 			       
                    310: 			       
                    311: 	} else {
                    312: 	    my $result =
                    313: 		'<p>'
                    314: 		.&mt('Overall result: [_1]',
                    315: 		     $record->{$version."resource.$respid.$partid.status"})
                    316: 		.'</p>';
                    317: 	    
                    318: 	    $result .= '<ul>';
                    319: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    320: 			     keys(%{$record}));
                    321: 	    foreach my $grade (sort(@grade)) {
                    322: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    323: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    324: 				     $dim, $record->{$grade}).
                    325: 			  '</li>';
                    326: 	    }
                    327: 	    $result.='</ul>';
                    328: 	    return $result;
                    329: 	}
                    330:        
1.122     ng        331:     }
1.118     ng        332:     return $answer;
                    333: }
                    334: 
                    335: #-- A couple of common js functions
                    336: sub commonJSfunctions {
                    337:     my $request = shift;
                    338:     $request->print(<<COMMONJSFUNCTIONS);
                    339: <script type="text/javascript" language="javascript">
                    340:     function radioSelection(radioButton) {
                    341: 	var selection=null;
                    342: 	if (radioButton.length > 1) {
                    343: 	    for (var i=0; i<radioButton.length; i++) {
                    344: 		if (radioButton[i].checked) {
                    345: 		    return radioButton[i].value;
                    346: 		}
                    347: 	    }
                    348: 	} else {
                    349: 	    if (radioButton.checked) return radioButton.value;
                    350: 	}
                    351: 	return selection;
                    352:     }
                    353: 
                    354:     function pullDownSelection(selectOne) {
                    355: 	var selection="";
                    356: 	if (selectOne.length > 1) {
                    357: 	    for (var i=0; i<selectOne.length; i++) {
                    358: 		if (selectOne[i].selected) {
                    359: 		    return selectOne[i].value;
                    360: 		}
                    361: 	    }
                    362: 	} else {
1.138     albertel  363:             // only one value it must be the selected one
                    364: 	    return selectOne.value;
1.118     ng        365: 	}
                    366:     }
                    367: </script>
                    368: COMMONJSFUNCTIONS
                    369: }
                    370: 
1.44      ng        371: #--- Dumps the class list with usernames,list of sections,
                    372: #--- section, ids and fullnames for each user.
                    373: sub getclasslist {
1.76      ng        374:     my ($getsec,$filterlist) = @_;
1.291     albertel  375:     my @getsec;
                    376:     if (!ref($getsec)) {
                    377: 	if ($getsec ne '' && $getsec ne 'all') {
                    378: 	    @getsec=($getsec);
                    379: 	}
                    380:     } else {
                    381: 	@getsec=@{$getsec};
                    382:     }
                    383:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
                    384: 
1.56      matthew   385:     my $classlist=&Apache::loncoursedata::get_classlist();
1.49      albertel  386:     # Bail out if we were unable to get the classlist
1.56      matthew   387:     return if (! defined($classlist));
                    388:     #
                    389:     my %sections;
                    390:     my %fullnames;
1.205     matthew   391:     foreach my $student (keys(%$classlist)) {
                    392:         my $end      = 
                    393:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    394:         my $start    = 
                    395:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    396:         my $id       = 
                    397:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    398:         my $section  = 
                    399:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    400:         my $fullname = 
                    401:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    402:         my $status   = 
                    403:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.76      ng        404: 	# filter students according to status selected
1.257     albertel  405: 	if ($filterlist && $env{'form.Status'} ne 'Any') {
                    406: 	    if ($env{'form.Status'} ne $status) {
1.205     matthew   407: 		delete ($classlist->{$student});
1.76      ng        408: 		next;
                    409: 	    }
                    410: 	}
1.205     matthew   411: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  412: 	if (&canview($section)) {
1.291     albertel  413: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  414: 		$sections{$section}++;
1.205     matthew   415: 		$fullnames{$student}=$fullname;
1.103     albertel  416: 	    } else {
1.205     matthew   417: 		delete($classlist->{$student});
1.103     albertel  418: 	    }
                    419: 	} else {
1.205     matthew   420: 	    delete($classlist->{$student});
1.103     albertel  421: 	}
1.44      ng        422:     }
                    423:     my %seen = ();
1.56      matthew   424:     my @sections = sort(keys(%sections));
                    425:     return ($classlist,\@sections,\%fullnames);
1.44      ng        426: }
                    427: 
1.103     albertel  428: sub canmodify {
                    429:     my ($sec)=@_;
                    430:     if ($perm{'mgr'}) {
                    431: 	if (!defined($perm{'mgr_section'})) {
                    432: 	    # can modify whole class
                    433: 	    return 1;
                    434: 	} else {
                    435: 	    if ($sec eq $perm{'mgr_section'}) {
                    436: 		#can modify the requested section
                    437: 		return 1;
                    438: 	    } else {
                    439: 		# can't modify the request section
                    440: 		return 0;
                    441: 	    }
                    442: 	}
                    443:     }
                    444:     #can't modify
                    445:     return 0;
                    446: }
                    447: 
                    448: sub canview {
                    449:     my ($sec)=@_;
                    450:     if ($perm{'vgr'}) {
                    451: 	if (!defined($perm{'vgr_section'})) {
                    452: 	    # can modify whole class
                    453: 	    return 1;
                    454: 	} else {
                    455: 	    if ($sec eq $perm{'vgr_section'}) {
                    456: 		#can modify the requested section
                    457: 		return 1;
                    458: 	    } else {
                    459: 		# can't modify the request section
                    460: 		return 0;
                    461: 	    }
                    462: 	}
                    463:     }
                    464:     #can't modify
                    465:     return 0;
                    466: }
                    467: 
1.44      ng        468: #--- Retrieve the grade status of a student for all the parts
                    469: sub student_gradeStatus {
1.324     albertel  470:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  471:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        472:     my %partstatus = ();
                    473:     foreach (@$partlist) {
1.128     ng        474: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        475: 	$status              = 'nothing' if ($status eq '');
                    476: 	$partstatus{$_}      = $status;
                    477: 	my $subkey           = "resource.$_.submitted_by";
                    478: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    479:     }
                    480:     return %partstatus;
                    481: }
                    482: 
1.45      ng        483: # hidden form and javascript that calls the form
                    484: # Use by verifyscript and viewgrades
                    485: # Shows a student's view of problem and submission
                    486: sub jscriptNform {
1.324     albertel  487:     my ($symb) = @_;
1.45      ng        488:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    489: 	'    function viewOneStudent(user,domain) {'."\n".
                    490: 	'	document.onestudent.student.value = user;'."\n".
                    491: 	'	document.onestudent.userdom.value = domain;'."\n".
                    492: 	'	document.onestudent.submit();'."\n".
                    493: 	'    }'."\n".
                    494: 	'</script>'."\n";
                    495:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
                    496: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.257     albertel  497: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    498: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
                    499: 	'<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.45      ng        500: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    501: 	'<input type="hidden" name="student" value="" />'."\n".
                    502: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    503: 	'</form>'."\n";
                    504:     return $jscript;
                    505: }
1.39      ng        506: 
1.315     bowersj2  507: # Given the score (as a number [0-1] and the weight) what is the final
                    508: # point value? This function will round to the nearest tenth, third,
                    509: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  510: sub compute_points {
1.315     bowersj2  511:     my ($score, $weight) = @_;
                    512:     
                    513:     my $tolerance = .00001;
                    514:     my $points = $score * $weight;
                    515: 
                    516:     # Check for nearness to 1/x.
                    517:     my $check_for_nearness = sub {
                    518:         my ($factor) = @_;
                    519:         my $num = ($points * $factor) + $tolerance;
                    520:         my $floored_num = floor($num);
1.316     albertel  521:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  522:             return $floored_num / $factor;
                    523:         }
                    524:         return $points;
                    525:     };
                    526: 
                    527:     $points = $check_for_nearness->(10);
                    528:     $points = $check_for_nearness->(3);
                    529:     $points = $check_for_nearness->(4);
                    530:     
                    531:     return $points;
                    532: }
                    533: 
1.44      ng        534: #------------------ End of general use routines --------------------
1.87      www       535: 
                    536: #
                    537: # Find most similar essay
                    538: #
                    539: 
                    540: sub most_similar {
                    541:     my ($uname,$udom,$uessay)=@_;
                    542: 
                    543: # ignore spaces and punctuation
                    544: 
                    545:     $uessay=~s/\W+/ /gs;
                    546: 
1.282     www       547: # ignore empty submissions (occuring when only files are sent)
                    548: 
                    549:     unless ($uessay=~/\w+/) { return ''; }
                    550: 
1.87      www       551: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       552:     my $limit=0.6;
1.87      www       553:     my $sname='';
                    554:     my $sdom='';
                    555:     my $scrsid='';
                    556:     my $sessay='';
                    557: # go through all essays ...
                    558:     foreach my $tkey (keys %oldessays) {
                    559: 	my ($tname,$tdom,$tcrsid)=split(/\./,$tkey);
                    560: # ... except the same student
1.88      www       561:         if (($tname ne $uname) || ($tdom ne $udom)) {
1.87      www       562: 	    my $tessay=$oldessays{$tkey};
                    563:             $tessay=~s/\W+/ /gs;
                    564: # String similarity gives up if not even limit
1.88      www       565:             my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       566: # Found one
                    567:             if ($tsimilar>$limit) {
                    568: 		$limit=$tsimilar;
                    569:                 $sname=$tname;
1.88      www       570:                 $sdom=$tdom;
1.87      www       571:                 $scrsid=$tcrsid;
                    572:                 $sessay=$oldessays{$tkey};
                    573:             }
                    574:         } 
                    575:     }
1.88      www       576:     if ($limit>0.6) {
1.87      www       577:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    578:     } else {
                    579:        return ('','','','',0);
                    580:     }
                    581: }
                    582: 
1.44      ng        583: #-------------------------------------------------------------------
                    584: 
                    585: #------------------------------------ Receipt Verification Routines
1.45      ng        586: #
1.44      ng        587: #--- Check whether a receipt number is valid.---
                    588: sub verifyreceipt {
                    589:     my $request  = shift;
                    590: 
1.257     albertel  591:     my $courseid = $env{'request.course.id'};
1.184     www       592:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  593: 	$env{'form.receipt'};
1.44      ng        594:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  595:     my ($symb)   = &get_symb($request);
1.44      ng        596: 
1.398     albertel  597:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
                    598: 	$receipt.'</h3></span>'."\n".
                    599: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
1.44      ng        600: 
                    601:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   602:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  603:     
                    604:     my $receiptparts=0;
1.390     albertel  605:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    606: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  607:     my $parts=['0'];
1.324     albertel  608:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.294     albertel  609:     foreach (sort 
                    610: 	     {
                    611: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    612: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    613: 		 }
                    614: 		 return $a cmp $b;
                    615: 	     } (keys(%$fullname))) {
1.44      ng        616: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  617: 	foreach my $part (@$parts) {
                    618: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
                    619: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
                    620: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
                    621: 		    '\')"; TARGET=_self>'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
                    622: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    623: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    624: 		if ($receiptparts) {
                    625: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    626: 		}
                    627: 		$contents.='</tr>'."\n";
                    628: 		
                    629: 		$matches++;
                    630: 	    }
1.44      ng        631: 	}
                    632:     }
                    633:     if ($matches == 0) {
                    634: 	$string = $title.'No match found for the above receipt.';
                    635:     } else {
1.324     albertel  636: 	$string = &jscriptNform($symb).$title.
1.44      ng        637: 	    'The above receipt matches the following student'.
                    638: 	    ($matches <= 1 ? '.' : 's.')."\n".
                    639: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                    640: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
                    641: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
                    642: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
1.177     albertel  643: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
                    644: 	if ($receiptparts) {
                    645: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
                    646: 	}
                    647: 	$string.='</tr>'."\n".$contents.
1.44      ng        648: 	    '</table></td></tr></table>'."\n";
                    649:     }
1.324     albertel  650:     return $string.&show_grading_menu_form($symb);
1.44      ng        651: }
                    652: 
                    653: #--- This is called by a number of programs.
                    654: #--- Called from the Grading Menu - View/Grade an individual student
                    655: #--- Also called directly when one clicks on the subm button 
                    656: #    on the problem page.
1.30      ng        657: sub listStudents {
1.41      ng        658:     my ($request) = shift;
1.49      albertel  659: 
1.324     albertel  660:     my ($symb) = &get_symb($request);
1.257     albertel  661:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    662:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    663:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                    664:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    665: 
                    666:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    667:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    668: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  669: 
1.398     albertel  670:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
                    671: 	' Submissions for a Student or a Group of Students</span></h3>';
1.118     ng        672: 
1.324     albertel  673:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  674: 
1.45      ng        675:     $request->print(<<LISTJAVASCRIPT);
                    676: <script type="text/javascript" language="javascript">
1.110     ng        677:     function checkSelect(checkBox) {
                    678: 	var ctr=0;
                    679: 	var sense="";
                    680: 	if (checkBox.length > 1) {
                    681: 	    for (var i=0; i<checkBox.length; i++) {
                    682: 		if (checkBox[i].checked) {
                    683: 		    ctr++;
                    684: 		}
                    685: 	    }
                    686: 	    sense = "a student or group of students";
                    687: 	} else {
                    688: 	    if (checkBox.checked) {
                    689: 		ctr = 1;
                    690: 	    }
                    691: 	    sense = "the student";
                    692: 	}
                    693: 	if (ctr == 0) {
1.126     ng        694: 	    alert("Please select "+sense+" before clicking on the Next button.");
1.110     ng        695: 	    return false;
                    696: 	}
                    697: 	document.gradesub.submit();
                    698:     }
                    699: 
                    700:     function reLoadList(formname) {
1.112     ng        701: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        702: 	formname.command.value = 'submission';
                    703: 	formname.submit();
                    704:     }
1.45      ng        705: </script>
                    706: LISTJAVASCRIPT
                    707: 
1.118     ng        708:     &commonJSfunctions($request);
1.41      ng        709:     $request->print($result);
1.39      ng        710: 
1.257     albertel  711:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked' : '';
1.119     ng        712:     my $checklastsub = $checkhdgrade eq '' ? 'checked' : '';
1.154     albertel  713:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
                    714: 	"\n".$table.
1.267     albertel  715: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="on" /> no </label>'."\n".
                    716: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
                    717: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
                    718: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
                    719: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
                    720: 	'<label><input type="radio" name="vAns" value="all" checked="on" /> all students </label><br />'."\n".
1.49      albertel  721: 	'&nbsp;<b>Submissions: </b>'."\n";
1.257     albertel  722:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.267     albertel  723: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
1.49      albertel  724:     }
1.110     ng        725: 
1.257     albertel  726:     my $saveStatus = $env{'form.Status'} eq '' ? 'Active' : $env{'form.Status'};
                    727:     $env{'form.Status'} = $saveStatus;
1.110     ng        728: 
1.267     albertel  729:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
                    730: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
                    731: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
1.348     bowersj2  732: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
                    733:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
                    734:         '<option value="1">Whole Points</option>'.
                    735:         '<option value=".5">Half Points</option>'.
1.349     albertel  736:         '<option value=".25">Quarter Points</option>'.
                    737:         '<option value=".1">Tenths of a Point</option>'.
1.348     bowersj2  738:         '</select>'.
                    739: 
1.45      ng        740: 	'<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
                    741: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  742: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    743: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    744: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    745: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.48      albertel  746: 	'<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
1.110     ng        747: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    748: 
1.257     albertel  749:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
                    750: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng        751:     } else {
                    752: 	$gradeTable.='<b>Student Status:</b> '.
                    753: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
                    754:     }
1.112     ng        755: 
1.126     ng        756:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    757: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
1.110     ng        758: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  759: 
                    760: # checkall buttons
                    761:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        762:     $gradeTable.='<input type="button" '."\n".
1.45      ng        763: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.249     albertel  764: 	'value="Next->" /> <br />'."\n";
                    765:     $gradeTable.=&check_buttons();
1.267     albertel  766:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="on" />Check For Plagiarism</label>';
1.249     albertel  767:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
1.45      ng        768:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
1.110     ng        769: 	'<table border="0"><tr bgcolor="#e6ffff">';
                    770:     my $loop = 0;
                    771:     while ($loop < 2) {
1.126     ng        772: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
1.250     albertel  773: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
1.301     albertel  774: 	if ($env{'form.showgrading'} eq 'yes' 
                    775: 	    && $submitonly ne 'queued'
                    776: 	    && $submitonly ne 'all') {
1.110     ng        777: 	    foreach (sort(@$partlist)) {
1.324     albertel  778: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
1.207     albertel  779: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
                    780: 		    ' Status&nbsp;</b></td>';
1.110     ng        781: 	    }
1.301     albertel  782: 	} elsif ($submitonly eq 'queued') {
                    783: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
1.110     ng        784: 	}
                    785: 	$loop++;
1.126     ng        786: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        787:     }
1.45      ng        788:     $gradeTable.='</tr>'."\n";
1.41      ng        789: 
1.45      ng        790:     my $ctr = 0;
1.294     albertel  791:     foreach my $student (sort 
                    792: 			 {
                    793: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    794: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    795: 			     }
                    796: 			     return $a cmp $b;
                    797: 			 }
                    798: 			 (keys(%$fullname))) {
1.41      ng        799: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  800: 
1.110     ng        801: 	my %status = ();
1.301     albertel  802: 
                    803: 	if ($submitonly eq 'queued') {
                    804: 	    my %queue_status = 
                    805: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    806: 							$udom,$uname);
                    807: 	    next if (!defined($queue_status{'gradingqueue'}));
                    808: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    809: 	}
                    810: 
                    811: 	if ($env{'form.showgrading'} eq 'yes' 
                    812: 	    && $submitonly ne 'queued'
                    813: 	    && $submitonly ne 'all') {
1.324     albertel  814: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  815: 	    my $submitted = 0;
1.164     albertel  816: 	    my $graded = 0;
1.248     albertel  817: 	    my $incorrect = 0;
1.110     ng        818: 	    foreach (keys(%status)) {
1.145     albertel  819: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  820: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    821: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    822: 		
1.110     ng        823: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    824: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  825: 		    $submitted = 0;
1.150     albertel  826: 		    my ($part)=split(/\./,$partid);
1.110     ng        827: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  828: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        829: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    830: 		}
1.41      ng        831: 	    }
1.248     albertel  832: 	    
1.156     albertel  833: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    834: 				     $submitonly eq 'incorrect' ||
                    835: 				     $submitonly eq 'graded'));
1.248     albertel  836: 	    next if (!$graded && ($submitonly eq 'graded'));
                    837: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        838: 	}
1.34      ng        839: 
1.45      ng        840: 	$ctr++;
1.249     albertel  841: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    842: 
1.104     albertel  843: 	if ( $perm{'vgr'} eq 'F' ) {
1.110     ng        844: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
1.126     ng        845: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  846:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    847:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    848: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    849: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
                    850: 	       '&nbsp;'.$section.'</td>'."\n";
1.110     ng        851: 
1.257     albertel  852: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        853: 		foreach (sort keys(%status)) {
                    854: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  855: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        856: 		}
1.41      ng        857: 	    }
1.126     ng        858: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.110     ng        859: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
1.41      ng        860: 	}
                    861:     }
1.110     ng        862:     if ($ctr%2 ==1) {
1.126     ng        863: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel  864: 	    if ($env{'form.showgrading'} eq 'yes' 
                    865: 		&& $submitonly ne 'queued'
                    866: 		&& $submitonly ne 'all') {
1.110     ng        867: 		foreach (@$partlist) {
                    868: 		    $gradeTable.='<td>&nbsp;</td>';
                    869: 		}
1.301     albertel  870: 	    } elsif ($submitonly eq 'queued') {
                    871: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng        872: 	    }
                    873: 	$gradeTable.='</tr>';
                    874:     }
                    875: 
1.249     albertel  876:     $gradeTable.='</table></td></tr></table>'."\n".
1.45      ng        877: 	'<input type="button" '.
                    878: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng        879: 	'value="Next->" /></form>'."\n";
1.45      ng        880:     if ($ctr == 0) {
1.96      albertel  881: 	my $num_students=(scalar(keys(%$fullname)));
                    882: 	if ($num_students eq 0) {
1.398     albertel  883: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel  884: 	} else {
1.171     albertel  885: 	    my $submissions='submissions';
                    886: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                    887: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel  888: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel  889: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel  890: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel  891: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel  892: 	}
1.46      ng        893:     } elsif ($ctr == 1) {
                    894: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
1.45      ng        895:     }
1.324     albertel  896:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng        897:     $request->print($gradeTable);
1.44      ng        898:     return '';
1.10      ng        899: }
                    900: 
1.44      ng        901: #---- Called from the listStudents routine
1.249     albertel  902: 
                    903: sub check_script {
                    904:     my ($form, $type)=@_;
                    905:     my $chkallscript='<script type="text/javascript">
                    906:     function checkall() {
                    907:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    908:             ele = document.forms.'.$form.'.elements[i];
                    909:             if (ele.name == "'.$type.'") {
                    910:             document.forms.'.$form.'.elements[i].checked=true;
                    911:                                        }
                    912:         }
                    913:     }
                    914: 
                    915:     function checksec() {
                    916:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    917:             ele = document.forms.'.$form.'.elements[i];
                    918:            string = document.forms.'.$form.'.chksec.value;
                    919:            if
                    920:           (ele.value.indexOf(":::SECTION"+string)>0) {
                    921:               document.forms.'.$form.'.elements[i].checked=true;
                    922:             }
                    923:         }
                    924:     }
                    925: 
                    926: 
                    927:     function uncheckall() {
                    928:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    929:             ele = document.forms.'.$form.'.elements[i];
                    930:             if (ele.name == "'.$type.'") {
                    931:             document.forms.'.$form.'.elements[i].checked=false;
                    932:                                        }
                    933:         }
                    934:     }
                    935: 
                    936: </script>'."\n";
                    937:     return $chkallscript;
                    938: }
                    939: 
                    940: sub check_buttons {
                    941:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                    942:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                    943:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                    944:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                    945:     return $buttons;
                    946: }
                    947: 
1.44      ng        948: #     Displays the submissions for one student or a group of students
1.34      ng        949: sub processGroup {
1.41      ng        950:     my ($request)  = shift;
                    951:     my $ctr        = 0;
1.155     albertel  952:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng        953:     my $total      = scalar(@stuchecked)-1;
1.45      ng        954: 
1.396     banghart  955:     foreach my $student (@stuchecked) {
                    956: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel  957: 	$env{'form.student'}        = $uname;
                    958: 	$env{'form.userdom'}        = $udom;
                    959: 	$env{'form.fullname'}       = $fullname;
1.41      ng        960: 	&submission($request,$ctr,$total);
                    961: 	$ctr++;
                    962:     }
                    963:     return '';
1.35      ng        964: }
1.34      ng        965: 
1.44      ng        966: #------------------------------------------------------------------------------------
                    967: #
                    968: #-------------------------- Next few routines handles grading by student, essentially
                    969: #                           handles essay response type problem/part
                    970: #
                    971: #--- Javascript to handle the submission page functionality ---
                    972: sub sub_page_js {
                    973:     my $request = shift;
                    974:     $request->print(<<SUBJAVASCRIPT);
                    975: <script type="text/javascript" language="javascript">
1.71      ng        976:     function updateRadio(formname,id,weight) {
1.125     ng        977: 	var gradeBox = formname["GD_BOX"+id];
                    978: 	var radioButton = formname["RADVAL"+id];
                    979: 	var oldpts = formname["oldpts"+id].value;
1.72      ng        980: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng        981: 	gradeBox.value = pts;
                    982: 	var resetbox = false;
                    983: 	if (isNaN(pts) || pts < 0) {
                    984: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                    985: 	    for (var i=0; i<radioButton.length; i++) {
                    986: 		if (radioButton[i].checked) {
                    987: 		    gradeBox.value = i;
                    988: 		    resetbox = true;
                    989: 		}
                    990: 	    }
                    991: 	    if (!resetbox) {
                    992: 		formtextbox.value = "";
                    993: 	    }
                    994: 	    return;
1.44      ng        995: 	}
1.71      ng        996: 
                    997: 	if (pts > weight) {
                    998: 	    var resp = confirm("You entered a value ("+pts+
                    999: 			       ") greater than the weight for the part. Accept?");
                   1000: 	    if (resp == false) {
1.125     ng       1001: 		gradeBox.value = oldpts;
1.71      ng       1002: 		return;
                   1003: 	    }
1.44      ng       1004: 	}
1.13      albertel 1005: 
1.71      ng       1006: 	for (var i=0; i<radioButton.length; i++) {
                   1007: 	    radioButton[i].checked=false;
                   1008: 	    if (pts == i && pts != "") {
                   1009: 		radioButton[i].checked=true;
                   1010: 	    }
                   1011: 	}
                   1012: 	updateSelect(formname,id);
1.125     ng       1013: 	formname["stores"+id].value = "0";
1.41      ng       1014:     }
1.5       albertel 1015: 
1.72      ng       1016:     function writeBox(formname,id,pts) {
1.125     ng       1017: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1018: 	if (checkSolved(formname,id) == 'update') {
                   1019: 	    gradeBox.value = pts;
                   1020: 	} else {
1.125     ng       1021: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1022: 	    gradeBox.value = oldpts;
1.125     ng       1023: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1024: 	    for (var i=0; i<radioButton.length; i++) {
                   1025: 		radioButton[i].checked=false;
1.72      ng       1026: 		if (i == oldpts) {
1.71      ng       1027: 		    radioButton[i].checked=true;
                   1028: 		}
                   1029: 	    }
1.41      ng       1030: 	}
1.125     ng       1031: 	formname["stores"+id].value = "0";
1.71      ng       1032: 	updateSelect(formname,id);
                   1033: 	return;
1.41      ng       1034:     }
1.44      ng       1035: 
1.71      ng       1036:     function clearRadBox(formname,id) {
                   1037: 	if (checkSolved(formname,id) == 'noupdate') {
                   1038: 	    updateSelect(formname,id);
                   1039: 	    return;
                   1040: 	}
1.125     ng       1041: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1042: 	for (var i=0; i<gradeSelect.length; i++) {
                   1043: 	    if (gradeSelect[i].selected) {
                   1044: 		var selectx=i;
                   1045: 	    }
                   1046: 	}
1.125     ng       1047: 	var stores = formname["stores"+id];
1.71      ng       1048: 	if (selectx == stores.value) { return };
1.125     ng       1049: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1050: 	gradeBox.value = "";
1.125     ng       1051: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1052: 	for (var i=0; i<radioButton.length; i++) {
                   1053: 	    radioButton[i].checked=false;
                   1054: 	}
                   1055: 	stores.value = selectx;
                   1056:     }
1.5       albertel 1057: 
1.71      ng       1058:     function checkSolved(formname,id) {
1.125     ng       1059: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1060: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1061: 	    if (!reply) {return "noupdate";}
1.120     ng       1062: 	    formname.overRideScore.value = 'yes';
1.41      ng       1063: 	}
1.71      ng       1064: 	return "update";
1.13      albertel 1065:     }
1.71      ng       1066: 
                   1067:     function updateSelect(formname,id) {
1.125     ng       1068: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1069: 	return;
1.41      ng       1070:     }
1.33      ng       1071: 
1.121     ng       1072: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1073:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1074: 	formname.gradeOpt.value = val;
1.71      ng       1075: 	if (val == "Save & Next") {
                   1076: 	    for (i=0;i<=total;i++) {
                   1077: 		for (j=0;j<parttot;j++) {
1.125     ng       1078: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1079: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1080: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1081: 			if (points == "") {
1.125     ng       1082: 			    var name = formname["name"+i].value;
1.129     ng       1083: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1084: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1085: 					       ", part "+partid+". Continue?");
1.71      ng       1086: 			    if (resp == false) {
1.125     ng       1087: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1088: 				return false;
                   1089: 			    }
                   1090: 			}
                   1091: 		    }
                   1092: 		    
                   1093: 		}
                   1094: 	    }
                   1095: 	    
                   1096: 	}
1.121     ng       1097: 	if (val == "Grade Student") {
                   1098: 	    formname.showgrading.value = "yes";
                   1099: 	    if (formname.Status.value == "") {
                   1100: 		formname.Status.value = "Active";
                   1101: 	    }
                   1102: 	    formname.studentNo.value = total;
                   1103: 	}
1.120     ng       1104: 	formname.submit();
                   1105:     }
                   1106: 
1.71      ng       1107: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1108:     function checkSubmitPage(formname,total) {
                   1109: 	noscore = new Array(100);
                   1110: 	var ptr = 0;
                   1111: 	for (i=1;i<total;i++) {
1.125     ng       1112: 	    var partid = formname["q_"+i].value;
1.127     ng       1113: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1114: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1115: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1116: 		if (points == "" && status != "correct_by_student") {
                   1117: 		    noscore[ptr] = i;
                   1118: 		    ptr++;
                   1119: 		}
                   1120: 	    }
                   1121: 	}
                   1122: 	if (ptr != 0) {
                   1123: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1124: 	    var prolist = "";
                   1125: 	    if (ptr == 1) {
                   1126: 		prolist = noscore[0];
                   1127: 	    } else {
                   1128: 		var i = 0;
                   1129: 		while (i < ptr-1) {
                   1130: 		    prolist += noscore[i]+", ";
                   1131: 		    i++;
                   1132: 		}
                   1133: 		prolist += "and "+noscore[i];
                   1134: 	    }
                   1135: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1136: 	    if (resp == false) {
                   1137: 		return false;
                   1138: 	    }
                   1139: 	}
1.45      ng       1140: 
1.71      ng       1141: 	formname.submit();
                   1142:     }
                   1143: </script>
                   1144: SUBJAVASCRIPT
                   1145: }
1.45      ng       1146: 
1.71      ng       1147: #--- javascript for essay type problem --
                   1148: sub sub_page_kw_js {
                   1149:     my $request = shift;
1.80      ng       1150:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1151:     &commonJSfunctions($request);
1.350     albertel 1152: 
1.351     albertel 1153:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1154:     <script text="text/javascript">
                   1155:     function checkInput() {
                   1156:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1157:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1158:       var usrctr = document.msgcenter.usrctr.value;
                   1159:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1160:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1161: 
                   1162:       var msgchk = "";
                   1163:       if (document.msgcenter.subchk.checked) {
                   1164:          msgchk = "msgsub,";
                   1165:       }
                   1166:       var includemsg = 0;
                   1167:       for (var i=1; i<=nmsg; i++) {
                   1168:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1169:           var frmmsg = document.msgcenter["msg"+i];
                   1170:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1171:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1172:           showflg.value = "1";
                   1173:           var chkbox = document.msgcenter["msgn"+i];
                   1174:           if (chkbox.checked) {
                   1175:              msgchk += "savemsg"+i+",";
                   1176:              includemsg = 1;
                   1177:           }
                   1178:       }
                   1179:       if (document.msgcenter.newmsgchk.checked) {
                   1180:          msgchk += "newmsg"+usrctr;
                   1181:          includemsg = 1;
                   1182:       }
                   1183:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1184:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1185:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1186:       includemsg.value = msgchk;
                   1187: 
                   1188:       self.close()
                   1189: 
                   1190:     }
                   1191:     </script>
                   1192: INNERJS
                   1193: 
1.351     albertel 1194:     my $inner_js_highlight_central=<<INNERJS;
                   1195:  <script type="text/javascript">
                   1196:     function updateChoice(flag) {
                   1197:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1198:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1199:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1200:       opener.document.SCORE.refresh.value = "on";
                   1201:       if (opener.document.SCORE.keywords.value!=""){
                   1202:          opener.document.SCORE.submit();
                   1203:       }
                   1204:       self.close()
                   1205:     }
                   1206: </script>
                   1207: INNERJS
                   1208: 
                   1209:     my $start_page_msg_central = 
                   1210:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1211: 				       {'js_ready'  => 1,
                   1212: 					'only_body' => 1,
                   1213: 					'bgcolor'   =>'#FFFFFF',});
                   1214:     my $end_page_msg_central = 
                   1215: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1216: 
                   1217: 
                   1218:     my $start_page_highlight_central = 
                   1219:         &Apache::loncommon::start_page('Highlight Central',
                   1220: 				       $inner_js_highlight_central,
1.350     albertel 1221: 				       {'js_ready'  => 1,
                   1222: 					'only_body' => 1,
                   1223: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1224:     my $end_page_highlight_central = 
1.350     albertel 1225: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1226: 
1.219     www      1227:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1228:     $docopen=~s/^document\.//;
1.71      ng       1229:     $request->print(<<SUBJAVASCRIPT);
                   1230: <script type="text/javascript" language="javascript">
1.45      ng       1231: 
1.44      ng       1232: //===================== Show list of keywords ====================
1.122     ng       1233:   function keywords(formname) {
                   1234:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1235:     if (nret==null) return;
1.122     ng       1236:     formname.keywords.value = nret;
1.44      ng       1237: 
1.122     ng       1238:     if (formname.keywords.value != "") {
1.128     ng       1239: 	formname.refresh.value = "on";
1.122     ng       1240: 	formname.submit();
1.44      ng       1241:     }
                   1242:     return;
                   1243:   }
                   1244: 
                   1245: //===================== Script to view submitted by ==================
                   1246:   function viewSubmitter(submitter) {
                   1247:     document.SCORE.refresh.value = "on";
                   1248:     document.SCORE.NCT.value = "1";
                   1249:     document.SCORE.unamedom0.value = submitter;
                   1250:     document.SCORE.submit();
                   1251:     return;
                   1252:   }
                   1253: 
                   1254: //===================== Script to add keyword(s) ==================
                   1255:   function getSel() {
                   1256:     if (document.getSelection) txt = document.getSelection();
                   1257:     else if (document.selection) txt = document.selection.createRange().text;
                   1258:     else return;
                   1259:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1260:     if (cleantxt=="") {
1.46      ng       1261: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1262: 	return;
                   1263:     }
                   1264:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1265:     if (nret==null) return;
1.127     ng       1266:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1267:     if (document.SCORE.keywords.value != "") {
1.127     ng       1268: 	document.SCORE.refresh.value = "on";
1.44      ng       1269: 	document.SCORE.submit();
                   1270:     }
                   1271:     return;
                   1272:   }
                   1273: 
                   1274: //====================== Script for composing message ==============
1.80      ng       1275:    // preload images
                   1276:    img1 = new Image();
                   1277:    img1.src = "$iconpath/mailbkgrd.gif";
                   1278:    img2 = new Image();
                   1279:    img2.src = "$iconpath/mailto.gif";
                   1280: 
1.44      ng       1281:   function msgCenter(msgform,usrctr,fullname) {
                   1282:     var Nmsg  = msgform.savemsgN.value;
                   1283:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1284:     var subject = msgform.msgsub.value;
1.127     ng       1285:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1286:     re = /msgsub/;
                   1287:     var shwsel = "";
                   1288:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1289:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1290:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1291:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1292: 	var testmsg = "savemsg"+i+",";
                   1293: 	re = new RegExp(testmsg,"g");
1.44      ng       1294: 	shwsel = "";
                   1295: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1296: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1297: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1298: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1299: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1300:     }
1.125     ng       1301:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1302:     shwsel = "";
                   1303:     re = /newmsg/;
                   1304:     if (re.test(msgchk)) { shwsel = "checked" }
                   1305:     newMsg(newmsg,shwsel);
                   1306:     msgTail(); 
                   1307:     return;
                   1308:   }
                   1309: 
1.123     ng       1310:   function checkEntities(strx) {
                   1311:     if (strx.length == 0) return strx;
                   1312:     var orgStr = ["&", "<", ">", '"']; 
                   1313:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1314:     var counter = 0;
                   1315:     while (counter < 4) {
                   1316: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1317: 	counter++;
                   1318:     }
                   1319:     return strx;
                   1320:   }
                   1321: 
                   1322:   function strReplace(strx, orgStr, newStr) {
                   1323:     return strx.split(orgStr).join(newStr);
                   1324:   }
                   1325: 
1.44      ng       1326:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1327:     var height = 70*Nmsg+250;
1.44      ng       1328:     var scrollbar = "no";
                   1329:     if (height > 600) {
                   1330: 	height = 600;
                   1331: 	scrollbar = "yes";
                   1332:     }
1.118     ng       1333:     var xpos = (screen.width-600)/2;
                   1334:     xpos = (xpos < 0) ? '0' : xpos;
                   1335:     var ypos = (screen.height-height)/2-30;
                   1336:     ypos = (ypos < 0) ? '0' : ypos;
                   1337: 
1.206     albertel 1338:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1339:     pWin.focus();
                   1340:     pDoc = pWin.document;
1.219     www      1341:     pDoc.$docopen;
1.351     albertel 1342:     pDoc.write('$start_page_msg_central');
1.76      ng       1343: 
                   1344:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1345:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.398     albertel 1346:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
1.76      ng       1347: 
                   1348:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1349:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1350:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1.44      ng       1351: }
                   1352:     function displaySubject(msg,shwsel) {
1.76      ng       1353:     pDoc = pWin.document;
                   1354:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1355:     pDoc.write("<td>Subject</td>");
                   1356:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1357:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1.44      ng       1358: }
                   1359: 
1.72      ng       1360:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1361:     pDoc = pWin.document;
                   1362:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1363:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
                   1364:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1365:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1.44      ng       1366: }
                   1367: 
                   1368:   function newMsg(newmsg,shwsel) {
1.76      ng       1369:     pDoc = pWin.document;
                   1370:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1371:     pDoc.write("<td align=\\"center\\">New</td>");
                   1372:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1373:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1.44      ng       1374: }
                   1375: 
                   1376:   function msgTail() {
1.76      ng       1377:     pDoc = pWin.document;
                   1378:     pDoc.write("</table>");
                   1379:     pDoc.write("</td></tr></table>&nbsp;");
                   1380:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1381:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1382:     pDoc.write("</form>");
1.351     albertel 1383:     pDoc.write('$end_page_msg_central');
1.128     ng       1384:     pDoc.close();
1.44      ng       1385: }
                   1386: 
                   1387: //====================== Script for keyword highlight options ==============
                   1388:   function kwhighlight() {
                   1389:     var kwclr    = document.SCORE.kwclr.value;
                   1390:     var kwsize   = document.SCORE.kwsize.value;
                   1391:     var kwstyle  = document.SCORE.kwstyle.value;
                   1392:     var redsel = "";
                   1393:     var grnsel = "";
                   1394:     var blusel = "";
                   1395:     if (kwclr=="red")   {var redsel="checked"};
                   1396:     if (kwclr=="green") {var grnsel="checked"};
                   1397:     if (kwclr=="blue")  {var blusel="checked"};
                   1398:     var sznsel = "";
                   1399:     var sz1sel = "";
                   1400:     var sz2sel = "";
                   1401:     if (kwsize=="0")  {var sznsel="checked"};
                   1402:     if (kwsize=="+1") {var sz1sel="checked"};
                   1403:     if (kwsize=="+2") {var sz2sel="checked"};
                   1404:     var synsel = "";
                   1405:     var syisel = "";
                   1406:     var sybsel = "";
                   1407:     if (kwstyle=="")    {var synsel="checked"};
                   1408:     if (kwstyle=="<i>") {var syisel="checked"};
                   1409:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1410:     highlightCentral();
                   1411:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1412:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1413:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1414:     highlightend();
                   1415:     return;
                   1416:   }
                   1417: 
                   1418:   function highlightCentral() {
1.76      ng       1419: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1420:     var xpos = (screen.width-400)/2;
                   1421:     xpos = (xpos < 0) ? '0' : xpos;
                   1422:     var ypos = (screen.height-330)/2-30;
                   1423:     ypos = (ypos < 0) ? '0' : ypos;
                   1424: 
1.206     albertel 1425:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1426:     hwdWin.focus();
                   1427:     var hDoc = hwdWin.document;
1.219     www      1428:     hDoc.$docopen;
1.351     albertel 1429:     hDoc.write('$start_page_highlight_central');
1.76      ng       1430:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.398     albertel 1431:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
1.76      ng       1432: 
                   1433:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1434:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1435:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1.44      ng       1436:   }
                   1437: 
                   1438:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1439:     var hDoc = hwdWin.document;
                   1440:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1441:     hDoc.write("<td align=\\"left\\">");
                   1442:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
                   1443:     hDoc.write("<td align=\\"left\\">");
                   1444:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
                   1445:     hDoc.write("<td align=\\"left\\">");
                   1446:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
                   1447:     hDoc.write("</tr>");
1.44      ng       1448:   }
                   1449: 
                   1450:   function highlightend() { 
1.76      ng       1451:     var hDoc = hwdWin.document;
                   1452:     hDoc.write("</table>");
                   1453:     hDoc.write("</td></tr></table>&nbsp;");
                   1454:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1455:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1456:     hDoc.write("</form>");
1.351     albertel 1457:     hDoc.write('$end_page_highlight_central');
1.128     ng       1458:     hDoc.close();
1.44      ng       1459:   }
                   1460: 
                   1461: </script>
                   1462: SUBJAVASCRIPT
                   1463: }
                   1464: 
1.349     albertel 1465: sub get_increment {
1.348     bowersj2 1466:     my $increment = $env{'form.increment'};
                   1467:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1468:         $increment != .1) {
                   1469:         $increment = 1;
                   1470:     }
                   1471:     return $increment;
                   1472: }
                   1473: 
1.71      ng       1474: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1475: sub gradeBox {
1.322     albertel 1476:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1477:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1478: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1479: 	'/check.gif" height="16" border="0" />';
                   1480:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
                   1481:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
1.398     albertel 1482: 		  '<span class="LC_info">problem weight assigned by computer</span>');
1.71      ng       1483:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1484:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1485: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1486:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.324     albertel 1487:     my $display_part=&get_display_part($partid,$symb);
1.270     albertel 1488:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1489: 				       [$partid]);
                   1490:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1491:     if ($last_resets{$partid}) {
                   1492:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1493:     }
1.71      ng       1494:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1495: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1496:     my $ctr = 0;
1.348     bowersj2 1497:     my $thisweight = 0;
1.349     albertel 1498:     my $increment = &get_increment();
1.71      ng       1499:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1500:     while ($thisweight<=$wgt) {
1.381     albertel 1501: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1502: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1503: 	    $thisweight.')" value="'.$thisweight.'" '.
1.381     albertel 1504: 	    ($score eq $thisweight ? 'checked':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1505: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1506:         $thisweight += $increment;
1.71      ng       1507: 	$ctr++;
                   1508:     }
                   1509:     $result.='</tr></table>';
                   1510:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1511:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1512: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1513: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1514: 	$wgt.')" /></td>'."\n";
                   1515:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1516: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1517: 	' </td><td>'."\n";
                   1518:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1519: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1520:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1521: 	$result.='<option></option>'.
1.125     ng       1522: 	    '<option selected="on">excused</option>';
1.71      ng       1523:     } else {
1.384     albertel 1524: 	$result.='<option selected="on"></option>'.
1.125     ng       1525: 	    '<option>excused</option>';
1.71      ng       1526:     }
1.125     ng       1527:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1528:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1529:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1530: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1531: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1532: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1533:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1534:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1535:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1536:         $aggtries.'" />'."\n";
1.71      ng       1537:     $result.='</td></tr></table>'."\n";
1.323     banghart 1538:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1539:     return $result;
                   1540: }
1.322     albertel 1541: 
                   1542: sub handback_box {
1.323     banghart 1543:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1544:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1545:     my (@respids);
1.375     albertel 1546:      my @part_response_id = &flatten_responseType($responseType);
                   1547:     foreach my $part_response_id (@part_response_id) {
                   1548:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1549:         if ($part eq $partid) {
1.375     albertel 1550:             push(@respids,$resp);
1.323     banghart 1551:         }
                   1552:     }
1.318     banghart 1553:     my $result;
1.323     banghart 1554:     foreach my $respid (@respids) {
1.322     albertel 1555: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1556: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1557: 	next if (!@$files);
                   1558: 	my $file_counter = 1;
1.313     banghart 1559: 	foreach my $file (@$files) {
1.368     banghart 1560: 	    if ($file =~ /\/portfolio\//) {
                   1561:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1562:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1563:     	        $file_disp = "$name.$ext";
                   1564:     	        $file = $file_path.$file_disp;
                   1565:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1566:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1567:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1568:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.369     banghart 1569:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1.368     banghart 1570:     	        $file_counter++;
                   1571: 	    }
1.322     albertel 1572: 	}
1.313     banghart 1573:     }
1.318     banghart 1574:     return $result;    
1.71      ng       1575: }
1.44      ng       1576: 
1.58      albertel 1577: sub show_problem {
1.382     albertel 1578:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1579:     my $rendered;
1.382     albertel 1580:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1581:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1582:     if ($mode eq 'both' or $mode eq 'text') {
                   1583: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1584: 						       $env{'request.course.id'},
                   1585: 						       undef,\%form);
1.144     albertel 1586:     }
1.58      albertel 1587:     if ($removeform) {
                   1588: 	$rendered=~s|<form(.*?)>||g;
                   1589: 	$rendered=~s|</form>||g;
1.374     albertel 1590: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1591:     }
1.144     albertel 1592:     my $companswer;
                   1593:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1594: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1595: 	$companswer=
                   1596: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1597: 						    $env{'request.course.id'},
                   1598: 						    %form);
1.144     albertel 1599:     }
1.58      albertel 1600:     if ($removeform) {
                   1601: 	$companswer=~s|<form(.*?)>||g;
                   1602: 	$companswer=~s|</form>||g;
1.144     albertel 1603: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1604:     }
                   1605:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1606:     $result.='<table border="0" width="100%">';
1.144     albertel 1607:     if ($viewon) {
                   1608: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1609: 	if ($mode eq 'both' or $mode eq 'text') {
                   1610: 	    $result.='View of the problem - ';
                   1611: 	} else {
                   1612: 	    $result.='Correct answer: ';
                   1613: 	}
1.257     albertel 1614: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1615:     }
                   1616:     if ($mode eq 'both') {
                   1617: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1618: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1619:     } elsif ($mode eq 'text') {
                   1620: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1621:     } elsif ($mode eq 'answer') {
                   1622: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1623:     }
1.58      albertel 1624:     $result.='</td></tr></table>';
                   1625:     $result.='</td></tr></table><br />';
1.71      ng       1626:     return $result;
1.58      albertel 1627: }
1.397     albertel 1628: 
1.396     banghart 1629: sub files_exist {
                   1630:     my ($r, $symb) = @_;
                   1631:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1632: 
1.396     banghart 1633:     foreach my $student (@students) {
                   1634:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1635:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1636: 					      $udom,$uname);
1.396     banghart 1637:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1638:         foreach my $submission (@$string) {
                   1639:             my ($partid,$respid) =
                   1640: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1641:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1642: 					   \%record);
                   1643:             return 1 if (@$files);
1.396     banghart 1644:         }
                   1645:     }
1.397     albertel 1646:     return 0;
1.396     banghart 1647: }
1.397     albertel 1648: 
1.394     banghart 1649: sub download_all_link {
                   1650:     my ($r,$symb) = @_;
1.395     albertel 1651:     my $all_students = 
                   1652: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1653: 
                   1654:     my $parts =
                   1655: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1656: 
1.394     banghart 1657:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1658:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1659:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1660:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1661:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1662: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1663:     return
                   1664: }
1.395     albertel 1665: 
1.44      ng       1666: # --------------------------- show submissions of a student, option to grade 
                   1667: sub submission {
                   1668:     my ($request,$counter,$total) = @_;
                   1669: 
1.257     albertel 1670:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1671:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1672:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1673:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.41      ng       1674: 
1.324     albertel 1675:     my $symb = &get_symb($request); 
                   1676:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1677: 
                   1678:     if (!&canview($usec)) {
1.398     albertel 1679: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1680: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1681: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1682: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1683: 	return;
                   1684:     }
                   1685: 
1.257     albertel 1686:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1687:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1688:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1689:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1690:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1691: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1692: 	'/check.gif" height="16" border="0" />';
1.41      ng       1693: 
                   1694:     # header info
                   1695:     if ($counter == 0) {
                   1696: 	&sub_page_js($request);
1.257     albertel 1697: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1698: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1699: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1700: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1701: 	    &download_all_link($request, $symb);
                   1702: 	}
1.398     albertel 1703: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
                   1704: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1.118     ng       1705: 
1.257     albertel 1706: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1707: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1708: 		$checkIcon.' symbol.'."\n";
                   1709: 	    $request->print($checkMark);
                   1710: 	}
1.41      ng       1711: 
1.44      ng       1712: 	# option to display problem, only once else it cause problems 
                   1713:         # with the form later since the problem has a form.
1.257     albertel 1714: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1715: 	    my $mode;
1.257     albertel 1716: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1717: 		$mode='both';
1.257     albertel 1718: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1719: 		$mode='text';
1.257     albertel 1720: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1721: 		$mode='answer';
                   1722: 	    }
1.329     albertel 1723: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1724: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1725: 	}
                   1726: 	
1.44      ng       1727: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1728:         # if this subroutine has been called once.
1.41      ng       1729: 	my %keyhash = ();
1.257     albertel 1730: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1731: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1732: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1733: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1734: 
1.257     albertel 1735: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1736: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1737: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1738: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1739: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1740: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1741: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1742: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1743: 	}
1.257     albertel 1744: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.44      ng       1745: 
1.303     banghart 1746: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1747: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1748: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
                   1749: 			'<input type="hidden" name="Status"     value="'.$env{'form.Status'}.'" />'."\n".
1.120     ng       1750: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1751: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1752: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1753: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1754: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.41      ng       1755: 			'<input type="hidden" name="symb"       value="'.$symb.'" />'."\n".
1.257     albertel 1756: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1757: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1758: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1759: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.326     albertel 1760: 			'<input type="hidden" name="section"    value="'.$env{'form.section'}.'" />'."\n".
                   1761: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1762: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1763: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1764: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1765: 	if ($env{'form.handgrade'} eq 'yes') {
                   1766: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1767: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1768: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1769: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1770: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1771: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1772: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1773: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1774: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1775: 	    }
1.123     ng       1776: 	}
1.41      ng       1777: 	
                   1778: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1779: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1780: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1781: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1782: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1783: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1784: 		'" />'."\n".
                   1785: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1786: 	    $cts++;
                   1787: 	}
                   1788: 	$request->print($prnmsg);
1.32      ng       1789: 
1.257     albertel 1790: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1791: #
                   1792: # Print out the keyword options line
                   1793: #
1.41      ng       1794: 	    $request->print(<<KEYWORDS);
1.38      ng       1795: &nbsp;<b>Keyword Options:</b>&nbsp;
1.122     ng       1796: <a href="javascript:keywords(document.SCORE)"; TARGET=_self>List</a>&nbsp; &nbsp;
1.38      ng       1797: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1798:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
                   1799: <a href="javascript:kwhighlight()"; TARGET=_self>Highlight Attribute</a><br /><br />
                   1800: KEYWORDS
1.88      www      1801: #
                   1802: # Load the other essays for similarity check
                   1803: #
1.324     albertel 1804:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1805: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1806: 	    $apath=&escape($apath);
1.88      www      1807: 	    $apath=~s/\W/\_/gs;
                   1808: 	    %oldessays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1809:         }
                   1810:     }
1.44      ng       1811: 
1.257     albertel 1812:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.71      ng       1813: 	$request->print('<br /><br /><br />') if ($counter > 0);
1.144     albertel 1814: 	my $mode;
1.257     albertel 1815: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1816: 	    $mode='both';
1.257     albertel 1817: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1818: 	    $mode='text';
1.257     albertel 1819: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1820: 	    $mode='answer';
                   1821: 	}
1.329     albertel 1822: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1823: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1824:     }
1.144     albertel 1825: 
1.257     albertel 1826:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1827:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1828: 
1.44      ng       1829:     # Display student info
1.41      ng       1830:     $request->print(($counter == 0 ? '' : '<br />'));
1.326     albertel 1831:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
                   1832: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1.44      ng       1833: 
1.257     albertel 1834:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1.45      ng       1835:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1836: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1837: 
1.118     ng       1838:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.45      ng       1839:     my @col_fullnames;
1.56      matthew  1840:     my ($classlist,$fullname);
1.257     albertel 1841:     if ($env{'form.handgrade'} eq 'yes') {
1.80      ng       1842: 	($classlist,undef,$fullname) = &getclasslist('all','0');
1.41      ng       1843: 	for (keys (%$handgrade)) {
1.44      ng       1844: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1.57      matthew  1845: 					    '.maxcollaborators',
                   1846:                                             $symb,$udom,$uname);
                   1847: 	    next if ($ncol <= 0);
                   1848:             s/\_/\./g;
                   1849:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
1.86      ng       1850:             my @goodcollaborators = ();
                   1851:             my @badcollaborators  = ();
                   1852: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
                   1853: 		$_ =~ s/[\$\^\(\)]//g;
                   1854: 		next if ($_ eq '');
1.80      ng       1855: 		my ($co_name,$co_dom) = split /\@|:/,$_;
1.86      ng       1856: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1.80      ng       1857: 		next if ($co_name eq $uname && $co_dom eq $udom);
1.86      ng       1858: 		# Doing this grep allows 'fuzzy' specification
                   1859: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
                   1860: 		if (! scalar(@Matches)) {
                   1861: 		    push @badcollaborators,$_;
                   1862: 		} else {
                   1863: 		    push @goodcollaborators, @Matches;
                   1864: 		}
1.80      ng       1865: 	    }
1.86      ng       1866:             if (scalar(@goodcollaborators) != 0) {
1.57      matthew  1867:                 $result.='<b>Collaborators: </b>';
1.86      ng       1868:                 foreach (@goodcollaborators) {
                   1869: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
                   1870: 		    push @col_fullnames, $givenn.' '.$lastname;
                   1871: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
                   1872: 		}
1.57      matthew  1873:                 $result.='<br />'."\n";
1.150     albertel 1874: 		my ($part)=split(/\./,$_);
1.86      ng       1875: 		$result.='<input type="hidden" name="collaborator'.$counter.
1.150     albertel 1876: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
                   1877: 		    "\n";
1.86      ng       1878: 	    }
                   1879: 	    if (scalar(@badcollaborators) > 0) {
                   1880: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1881: 		$result.='This student has submitted ';
                   1882: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
                   1883: 		$result .= ': '.join(', ',@badcollaborators);
                   1884: 		$result .= '</td></tr></table>';
                   1885: 	    }         
                   1886: 	    if (scalar(@badcollaborators > $ncol)) {
                   1887: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1888: 		$result .= 'This student has submitted too many '.
                   1889: 		    'collaborators.  Maximum is '.$ncol.'.';
                   1890: 		$result .= '</td></tr></table>';
                   1891: 	    }
1.41      ng       1892: 	}
                   1893:     }
1.44      ng       1894:     $request->print($result."\n");
1.33      ng       1895: 
1.44      ng       1896:     # print student answer/submission
                   1897:     # Options are (1) Handgaded submission only
                   1898:     #             (2) Last submission, includes submission that is not handgraded 
                   1899:     #                  (for multi-response type part)
                   1900:     #             (3) Last submission plus the parts info
                   1901:     #             (4) The whole record for this student
1.257     albertel 1902:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 1903: 	my ($string,$timestamp)= &get_last_submission(\%record);
                   1904: 	my $lastsubonly=''.
                   1905: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
                   1906: 	     $$timestamp)."</td></tr>\n";
                   1907: 	if ($$timestamp eq '') {
                   1908: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
                   1909: 	} else {
                   1910: 	    my %seenparts;
1.375     albertel 1911: 	    my @part_response_id = &flatten_responseType($responseType);
                   1912: 	    foreach my $part (@part_response_id) {
1.393     albertel 1913: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   1914: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   1915: 
1.375     albertel 1916: 		my ($partid,$respid) = @{ $part };
1.324     albertel 1917: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 1918: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 1919: 		    if (exists($seenparts{$partid})) { next; }
                   1920: 		    $seenparts{$partid}=1;
1.207     albertel 1921: 		    my $submitby='<b>Part:</b> '.$display_part.
                   1922: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 1923: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 1924: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.151     albertel 1925: 			'\')"; TARGET=_self>'.
1.257     albertel 1926: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 1927: 		    $request->print($submitby);
                   1928: 		    next;
                   1929: 		}
                   1930: 		my $responsetype = $responseType->{$partid}->{$respid};
                   1931: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.207     albertel 1932: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1.398     albertel 1933: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   1934: 			' )</span>&nbsp; &nbsp;'.
                   1935: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1.151     albertel 1936: 		    next;
                   1937: 		}
                   1938: 		foreach (@$string) {
                   1939: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1.375     albertel 1940: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.151     albertel 1941: 		    my ($ressub,$subval) = split(/:/,$_,2);
                   1942: 		    # Similarity check
                   1943: 		    my $similar='';
1.257     albertel 1944: 		    if($env{'form.checkPlag'}){
1.151     albertel 1945: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   1946: 			    &most_similar($uname,$udom,$subval);
                   1947: 			if ($osim) {
                   1948: 			    $osim=int($osim*100.0);
1.398     albertel 1949: 			    $similar="<hr /><h3><span class=\"LC_warning\">Essay".
1.151     albertel 1950: 				" is $osim% similar to an essay by ".
                   1951: 				&Apache::loncommon::plainname($oname,$odom).
1.398     albertel 1952: 				'</span></h3><blockquote><i>'.
1.151     albertel 1953: 				&keywords_highlight($oessay).
                   1954: 				'</i></blockquote><hr />';
                   1955: 			}
1.150     albertel 1956: 		    }
1.151     albertel 1957: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 1958: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   1959: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 1960: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 1961: 			my $display_part=&get_display_part($partid,$symb);
1.393     albertel 1962: 			$lastsubonly.='<tr><td bgcolor="#ffffe6">Debug -'.'<b>Part:</b> '.
1.398     albertel 1963: 			    $display_part.' <span class="LC_internal_info">( hhhh ID '.$respid.
                   1964: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 1965: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   1966: 			if (@$files) {
1.398     albertel 1967: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1.303     banghart 1968: 			    my $file_counter = 0;
1.313     banghart 1969: 			    foreach my $file (@$files) {
1.303     banghart 1970: 			        $file_counter ++;
1.232     albertel 1971: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 1972: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 1973: 			    }
1.236     albertel 1974: 			    $lastsubonly.='<br />';
1.41      ng       1975: 			}
1.151     albertel 1976: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   1977: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   1978: 					 $respid,\%record,$order);
                   1979: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       1980: 		    }
                   1981: 		}
                   1982: 	    }
1.151     albertel 1983: 	}
                   1984: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   1985: 	$request->print($lastsubonly);
1.257     albertel 1986:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 1987: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 1988: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 1989:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       1990: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 1991: 								 $env{'request.course.id'},
1.44      ng       1992: 								 $last,'.submission',
                   1993: 								 'Apache::grades::keywords_highlight'));
1.41      ng       1994:     }
1.120     ng       1995: 
1.121     ng       1996:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   1997: 	.$udom.'" />'."\n");
1.41      ng       1998:     
1.44      ng       1999:     # return if view submission with no grading option
1.257     albertel 2000:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2001: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2002: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
                   2003: 	    .$counter.'\');" TARGET=_self> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 2004: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 2005: 	if (($env{'form.command'} eq 'submission') || 
                   2006: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2007: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2008: 	}
1.180     albertel 2009: 	$request->print($toGrade);
1.41      ng       2010: 	return;
1.180     albertel 2011:     } else {
                   2012: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       2013:     }
1.33      ng       2014: 
1.121     ng       2015:     # essay grading message center
1.257     albertel 2016:     if ($env{'form.handgrade'} eq 'yes') {
                   2017: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2018: 	my $msgfor = $givenn.' '.$lastname;
                   2019: 	if (scalar(@col_fullnames) > 0) {
                   2020: 	    my $lastone = pop @col_fullnames;
                   2021: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   2022: 	}
                   2023: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       2024: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2025: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2026: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.118     ng       2027: 	    ',\''.$msgfor.'\')"; TARGET=_self>'.
1.350     albertel 2028: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
                   2029: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2030: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2031: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2032: 	    '<br />&nbsp;('.
                   2033: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       2034: 	$request->print($result);
1.118     ng       2035:     }
1.300     albertel 2036:     if ($perm{'vgr'}) {
1.297     www      2037: 	$request->print('<br />'.
1.300     albertel 2038: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2039: 						   $uname,$udom,'check'));
1.297     www      2040:     }
1.300     albertel 2041:     if ($perm{'opa'}) {
1.297     www      2042: 	$request->print('<br />'.
1.300     albertel 2043: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2044: 					 $uname,$udom,$symb,'check'));
1.297     www      2045:     }
1.41      ng       2046: 
                   2047:     my %seen = ();
                   2048:     my @partlist;
1.129     ng       2049:     my @gradePartRespid;
1.375     albertel 2050:     my @part_response_id = &flatten_responseType($responseType);
                   2051:     foreach my $part_response_id (@part_response_id) {
                   2052:     	my ($partid,$respid) = @{ $part_response_id };
                   2053: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2054: 	next if ($seen{$partid} > 0);
1.41      ng       2055: 	$seen{$partid}++;
1.393     albertel 2056: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2057: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2058: 	push @partlist,$partid;
1.129     ng       2059: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2060: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2061:     }
1.45      ng       2062:     $result='<input type="hidden" name="partlist'.$counter.
                   2063: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2064:     $result.='<input type="hidden" name="gradePartRespid'.
                   2065: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2066:     my $ctr = 0;
                   2067:     while ($ctr < scalar(@partlist)) {
                   2068: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2069: 	    $partlist[$ctr].'" />'."\n";
                   2070: 	$ctr++;
                   2071:     }
                   2072:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       2073: 
                   2074:     # print end of form
                   2075:     if ($counter == $total) {
1.297     www      2076: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2077: 	$endform.='<input type="button" value="Save & Next" '.
                   2078: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
                   2079: 	    $total.','.scalar(@partlist).');" TARGET=_self> &nbsp;'."\n";
                   2080: 	my $ntstu ='<select name="NTSTU">'.
                   2081: 	    '<option>1</option><option>2</option>'.
                   2082: 	    '<option>3</option><option>5</option>'.
                   2083: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2084: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.119     ng       2085: 	$ntstu =~ s/<option>$nsel</<option selected="on">$nsel</;
                   2086: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2087: 	$endform.='<input type="button" value="Previous" '.
                   2088: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" TARGET=_self> &nbsp;'."\n".
                   2089: 	    '<input type="button" value="Next" '.
                   2090: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" TARGET=_self> &nbsp;';
                   2091: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2092:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2093:             "' name='increment' />";
1.45      ng       2094: 	$endform.='</td><tr></table></form>';
1.324     albertel 2095: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2096: 	$request->print($endform);
                   2097:     }
                   2098:     return '';
1.38      ng       2099: }
                   2100: 
1.44      ng       2101: #--- Retrieve the last submission for all the parts
1.38      ng       2102: sub get_last_submission {
1.119     ng       2103:     my ($returnhash)=@_;
1.46      ng       2104:     my (@string,$timestamp);
1.119     ng       2105:     if ($$returnhash{'version'}) {
1.46      ng       2106: 	my %lasthash=();
                   2107: 	my ($version);
1.119     ng       2108: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2109: 	    foreach my $key (sort(split(/\:/,
                   2110: 					$$returnhash{$version.':keys'}))) {
                   2111: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2112: 		$timestamp = 
                   2113: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2114: 	    }
                   2115: 	}
1.397     albertel 2116: 	foreach my $key (keys(%lasthash)) {
                   2117: 	    next if ($key !~ /\.submission$/);
                   2118: 
                   2119: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2120: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2121: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2122: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2123: 	}
                   2124:     }
1.397     albertel 2125:     if (!@string) {
                   2126: 	$string[0] =
1.398     albertel 2127: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2128:     }
                   2129:     return (\@string,\$timestamp);
1.38      ng       2130: }
1.35      ng       2131: 
1.44      ng       2132: #--- High light keywords, with style choosen by user.
1.38      ng       2133: sub keywords_highlight {
1.44      ng       2134:     my $string    = shift;
1.257     albertel 2135:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2136:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2137:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2138:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2139:     foreach my $keyword (@keylist) {
                   2140: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2141:     }
                   2142:     return $string;
1.38      ng       2143: }
1.36      ng       2144: 
1.44      ng       2145: #--- Called from submission routine
1.38      ng       2146: sub processHandGrade {
1.41      ng       2147:     my ($request) = shift;
1.324     albertel 2148:     my $symb   = &get_symb($request);
                   2149:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2150:     my $button = $env{'form.gradeOpt'};
                   2151:     my $ngrade = $env{'form.NCT'};
                   2152:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2153:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2154:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2155: 
1.44      ng       2156:     if ($button eq 'Save & Next') {
                   2157: 	my $ctr = 0;
                   2158: 	while ($ctr < $ngrade) {
1.257     albertel 2159: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2160: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2161: 	    if ($errorflag eq 'no_score') {
                   2162: 		$ctr++;
                   2163: 		next;
                   2164: 	    }
1.104     albertel 2165: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2166: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2167: 		$ctr++;
                   2168: 		next;
                   2169: 	    }
1.257     albertel 2170: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2171: 	    my ($subject,$message,$msgstatus) = ('','','');
1.386     raeburn  2172:             my $restitle = &Apache::lonnet::gettitle($symb);
                   2173:             my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2174:                                                 $symb,$udom,$uname);
                   2175:             my ($feedurl,$baseurl,$showsymb,$messagetail);
                   2176:             $feedurl = &Apache::lonnet::clutter($url);
                   2177:             if ($encrypturl =~ /^yes$/i) {
                   2178:                 $baseurl = &Apache::lonenc::encrypted($feedurl,1);
                   2179:                 $showsymb = &Apache::lonenc::encrypted($symb,1);
1.387     raeburn  2180:             } else {
                   2181:                 $baseurl = $feedurl;
                   2182:                 $showsymb = $symb;
1.386     raeburn  2183:             }
1.62      albertel 2184: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2185: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2186: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2187: 		$subject.=' ['.$restitle.']';
1.44      ng       2188: 		my (@msgnum) = split(/,/,$includemsg);
                   2189: 		foreach (@msgnum) {
1.257     albertel 2190: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2191: 		}
1.80      ng       2192: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2193: 		if ($env{'form.withgrades'.$ctr}) {
                   2194: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2195: 		    $messagetail = " for <a href=\"".
                   2196: 		                   $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
                   2197: 		}
                   2198: 		$msgstatus = 
                   2199:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2200: 						     $message.$messagetail,
                   2201:                                                      undef,$baseurl,undef,
                   2202:                                                      undef,undef,$showsymb,
                   2203:                                                      $restitle);
                   2204: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2205: 				$msgstatus);
1.44      ng       2206: 	    }
1.257     albertel 2207: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2208: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2209: 		foreach my $collabstr (@collabstrs) {
                   2210: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2211: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2212: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2213: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2214: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2215: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2216: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2217: 			    next;
                   2218: 			} else {
                   2219: 			    if ($message ne '') {
1.386     raeburn  2220:                                 $encrypturl=
                   2221:                                   &Apache::lonnet::EXT('resource.0.encrypturl',
                   2222:                                                        $symb,$udom,$collaborator);
                   2223:                                 if ($encrypturl =~ /^yes$/i) {
                   2224:                                     $baseurl = &Apache::lonenc::encrypted($feedurl,1);
                   2225:                                     $showsymb = &Apache::lonenc::encrypted($symb,1);
                   2226:                                 } else {
                   2227:                                     $baseurl = $feedurl;
                   2228:                                     $showsymb = $symb;
                   2229:                                 }
                   2230:                                 if ($env{'form.withgrades'.$ctr}) {
                   2231:                                     $messagetail = " for <a href=\"".
                   2232:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
                   2233: 
                   2234:                                 }
                   2235: 				$msgstatus = 
                   2236:                                     &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.150     albertel 2237: 			    }
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.398     albertel 2568:                         $request->print('<span class="LC_error">An errror occured ('.$result.
                   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.";
                   2591: 		my $url = (&Apache::lonnet::decode_symb($symb))[2];
1.388     raeburn  2592: 		my $feedurl = &Apache::lonnet::clutter($url);
1.386     raeburn  2593:                 my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2594:                                                     $symb,$domain,$stuname);
                   2595:                 my ($baseurl,$showsymb);
                   2596:                 if ($encrypturl =~ /^yes$/i) {
                   2597:                     $baseurl = &Apache::lonenc::encrypted($feedurl,1);
                   2598:                     $showsymb = &Apache::lonenc::encrypted($symb,1);
                   2599:                 } else {
                   2600:                     $baseurl = $feedurl;
                   2601:                     $showsymb = $symb;
                   2602:                 }
                   2603:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2604: 		my $msgstatus = 
                   2605:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2606: 			 ' (File Returned) ['.$restitle.']',$message,undef,
                   2607:                          $baseurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2608:             }
                   2609:         }
1.338     banghart 2610:     return;
1.337     banghart 2611: }
                   2612: 
1.313     banghart 2613: sub get_submitted_files {
                   2614:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2615:     my @files;
                   2616:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2617:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2618:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2619:     	    push(@files,$file_url.$file);
                   2620:         }
                   2621:     }
                   2622:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2623:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2624:     }
                   2625:     return (\@files);
                   2626: }
1.322     albertel 2627: 
1.269     raeburn  2628: # ----------- Provides number of tries since last reset.
                   2629: sub get_num_tries {
                   2630:     my ($record,$last_reset,$part) = @_;
                   2631:     my $timestamp = '';
                   2632:     my $num_tries = 0;
                   2633:     if ($$record{'version'}) {
                   2634:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2635:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2636:                 $timestamp = $$record{$version.':timestamp'};
                   2637:                 if ($timestamp > $last_reset) {
                   2638:                     $num_tries ++;
                   2639:                 } else {
                   2640:                     last;
                   2641:                 }
                   2642:             }
                   2643:         }
                   2644:     }
                   2645:     return $num_tries;
                   2646: }
                   2647: 
                   2648: # ----------- Determine decrements required in aggregate totals 
                   2649: sub decrement_aggs {
                   2650:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2651:     my %decrement = (
                   2652:                         attempts => 0,
                   2653:                         users => 0,
                   2654:                         correct => 0
                   2655:                     );
                   2656:     $decrement{'attempts'} = $aggtries;
                   2657:     if ($solvedstatus =~ /^correct/) {
                   2658:         $decrement{'correct'} = 1;
                   2659:     }
                   2660:     if ($aggtries == $totaltries) {
                   2661:         $decrement{'users'} = 1;
                   2662:     }
                   2663:     foreach my $type (keys (%decrement)) {
                   2664:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2665:     }
                   2666:     return;
                   2667: }
                   2668: 
                   2669: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2670: sub get_last_resets {
1.270     albertel 2671:     my ($symb,$courseid,$partids) =@_;
                   2672:     my %last_resets;
1.269     raeburn  2673:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2674:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2675:     my @keys;
                   2676:     foreach my $part (@{$partids}) {
                   2677: 	push(@keys,"$symb\0$part\0resettime");
                   2678:     }
                   2679:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2680: 				     $cdom,$cname);
                   2681:     foreach my $part (@{$partids}) {
                   2682: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2683:     }
1.270     albertel 2684:     return %last_resets;
1.269     raeburn  2685: }
                   2686: 
1.251     banghart 2687: # ----------- Handles creating versions for portfolio files as answers
                   2688: sub version_portfiles {
1.343     banghart 2689:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2690:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2691:     my @returned_keys;
1.255     banghart 2692:     my $parts = join('|', @$parts_graded);
1.359     www      2693:     my $portfolio_root = &propath($domain,$stu_name).
                   2694: 	'/userfiles/portfolio';
1.277     albertel 2695:     foreach my $key (keys(%$record)) {
1.259     banghart 2696:         my $new_portfiles;
1.263     banghart 2697:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2698:             my @versioned_portfiles;
1.367     albertel 2699:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2700:             foreach my $file (@portfiles) {
1.306     banghart 2701:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2702:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2703: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2704: 		    &file_name_version_ext($answer_file);
1.306     banghart 2705:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2706:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2707:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2708:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2709:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2710:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2711:                         [$directory.$new_answer],
1.306     banghart 2712:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2713:                 }
1.252     banghart 2714:             }
1.343     banghart 2715:             $$record{$key} = join(',',@versioned_portfiles);
                   2716:             push(@returned_keys,$key);
1.251     banghart 2717:         }
                   2718:     } 
1.343     banghart 2719:     return (@returned_keys);   
1.305     banghart 2720: }
                   2721: 
1.307     banghart 2722: sub get_next_version {
1.341     banghart 2723:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2724:     my $version;
                   2725:     foreach my $row (@$dir_list) {
                   2726:         my ($file) = split(/\&/,$row,2);
                   2727:         my ($file_name,$file_version,$file_ext) =
                   2728: 	    &file_name_version_ext($file);
                   2729:         if (($file_name eq $answer_name) && 
                   2730: 	    ($file_ext eq $answer_ext)) {
                   2731:                 # gets here if filename and extension match, regardless of version
                   2732:                 if ($file_version ne '') {
                   2733:                 # a versioned file is found  so save it for later
                   2734:                 if ($file_version > $version) {
                   2735: 		    $version = $file_version;
                   2736: 	        }
                   2737:             }
                   2738:         }
                   2739:     } 
                   2740:     $version ++;
                   2741:     return($version);
                   2742: }
                   2743: 
1.305     banghart 2744: sub version_selected_portfile {
1.306     banghart 2745:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2746:     my ($answer_name,$answer_ver,$answer_ext) =
                   2747:         &file_name_version_ext($file_name);
                   2748:     my $new_answer;
                   2749:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2750:     if($env{'form.copy'} eq '-1') {
                   2751:         &Apache::lonnet::logthis('problem getting file '.$file_name);
                   2752:         $new_answer = 'problem getting file';
                   2753:     } else {
                   2754:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2755:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2756:                             $stu_name,$domain,'copy',
                   2757: 		        '/portfolio'.$directory.$new_answer);
                   2758:     }    
                   2759:     return ($new_answer);
1.251     banghart 2760: }
                   2761: 
1.304     albertel 2762: sub file_name_version_ext {
                   2763:     my ($file)=@_;
                   2764:     my @file_parts = split(/\./, $file);
                   2765:     my ($name,$version,$ext);
                   2766:     if (@file_parts > 1) {
                   2767: 	$ext=pop(@file_parts);
                   2768: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2769: 	    $version=pop(@file_parts);
                   2770: 	}
                   2771: 	$name=join('.',@file_parts);
                   2772:     } else {
                   2773: 	$name=join('.',@file_parts);
                   2774:     }
                   2775:     return($name,$version,$ext);
                   2776: }
                   2777: 
1.44      ng       2778: #--------------------------------------------------------------------------------------
                   2779: #
                   2780: #-------------------------- Next few routines handles grading by section or whole class
                   2781: #
                   2782: #--- Javascript to handle grading by section or whole class
1.42      ng       2783: sub viewgrades_js {
                   2784:     my ($request) = shift;
                   2785: 
1.41      ng       2786:     $request->print(<<VIEWJAVASCRIPT);
                   2787: <script type="text/javascript" language="javascript">
1.45      ng       2788:    function writePoint(partid,weight,point) {
1.125     ng       2789: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2790: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2791: 	if (point == "textval") {
1.125     ng       2792: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2793: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2794: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2795: 		var resetbox = false;
                   2796: 		for (var i=0; i<radioButton.length; i++) {
                   2797: 		    if (radioButton[i].checked) {
                   2798: 			textbox.value = i;
                   2799: 			resetbox = true;
                   2800: 		    }
                   2801: 		}
                   2802: 		if (!resetbox) {
                   2803: 		    textbox.value = "";
                   2804: 		}
                   2805: 		return;
                   2806: 	    }
1.109     matthew  2807: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2808: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2809: 				   ") greater than the weight for the part. Accept?");
                   2810: 		if (resp == false) {
                   2811: 		    textbox.value = "";
                   2812: 		    return;
                   2813: 		}
                   2814: 	    }
1.42      ng       2815: 	    for (var i=0; i<radioButton.length; i++) {
                   2816: 		radioButton[i].checked=false;
1.109     matthew  2817: 		if (parseFloat(point) == i) {
1.42      ng       2818: 		    radioButton[i].checked=true;
                   2819: 		}
                   2820: 	    }
1.41      ng       2821: 
1.42      ng       2822: 	} else {
1.125     ng       2823: 	    textbox.value = parseFloat(point);
1.42      ng       2824: 	}
1.41      ng       2825: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2826: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2827: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2828: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2829: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2830: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2831: 	    if (saveval != "correct") {
                   2832: 		scorename.value = point;
1.43      ng       2833: 		if (selname[0].selected != true) {
                   2834: 		    selname[0].selected = true;
                   2835: 		}
1.42      ng       2836: 	    }
                   2837: 	}
1.125     ng       2838: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2839:     }
                   2840: 
                   2841:     function writeRadText(partid,weight) {
1.125     ng       2842: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2843: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2844:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2845: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2846: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2847: 	    for (var i=0; i<radioButton.length; i++) {
                   2848: 		radioButton[i].checked=false;
                   2849: 
                   2850: 	    }
                   2851: 	    textbox.value = "";
                   2852: 
                   2853: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2854: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2855: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2856: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2857: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2858: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2859: 		if ((saveval != "correct") || override) {
1.42      ng       2860: 		    scorename.value = "";
1.125     ng       2861: 		    if (selval[1].selected) {
                   2862: 			selname[1].selected = true;
                   2863: 		    } else {
                   2864: 			selname[2].selected = true;
                   2865: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   2866: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   2867: 		    }
1.42      ng       2868: 		}
                   2869: 	    }
1.43      ng       2870: 	} else {
                   2871: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2872: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2873: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2874: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2875: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2876: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2877: 		if ((saveval != "correct") || override) {
1.125     ng       2878: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       2879: 		    selname[0].selected = true;
                   2880: 		}
                   2881: 	    }
                   2882: 	}	    
1.42      ng       2883:     }
                   2884: 
                   2885:     function changeSelect(partid,user) {
1.125     ng       2886: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2887: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       2888: 	var point  = textbox.value;
1.125     ng       2889: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       2890: 
1.109     matthew  2891: 	if (isNaN(point) || parseFloat(point) < 0) {
                   2892: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       2893: 	    textbox.value = "";
                   2894: 	    return;
                   2895: 	}
1.109     matthew  2896: 	if (parseFloat(point) > parseFloat(weight)) {
                   2897: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2898: 			       ") greater than the weight of the part. Accept?");
                   2899: 	    if (resp == false) {
                   2900: 		textbox.value = "";
                   2901: 		return;
                   2902: 	    }
                   2903: 	}
1.42      ng       2904: 	selval[0].selected = true;
                   2905:     }
                   2906: 
                   2907:     function changeOneScore(partid,user) {
1.125     ng       2908: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2909: 	if (selval[1].selected || selval[2].selected) {
                   2910: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   2911: 	    if (selval[2].selected) {
                   2912: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   2913: 	    }
1.269     raeburn  2914:         }
1.42      ng       2915:     }
                   2916: 
                   2917:     function resetEntry(numpart) {
                   2918: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       2919: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   2920: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   2921: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   2922: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       2923: 	    for (var i=0; i<radioButton.length; i++) {
                   2924: 		radioButton[i].checked=false;
                   2925: 
                   2926: 	    }
                   2927: 	    textbox.value = "";
                   2928: 	    selval[0].selected = true;
                   2929: 
                   2930: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2931: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2932: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2933: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2934: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   2935: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   2936: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   2937: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2938: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2939: 		if (saveselval == "excused") {
1.43      ng       2940: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       2941: 		} else {
1.43      ng       2942: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       2943: 		}
                   2944: 	    }
1.41      ng       2945: 	}
1.42      ng       2946:     }
                   2947: 
1.41      ng       2948: </script>
                   2949: VIEWJAVASCRIPT
1.42      ng       2950: }
                   2951: 
1.44      ng       2952: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       2953: sub viewgrades {
                   2954:     my ($request) = shift;
                   2955:     &viewgrades_js($request);
1.41      ng       2956: 
1.324     albertel 2957:     my ($symb) = &get_symb($request);
1.168     albertel 2958:     #need to make sure we have the correct data for later EXT calls, 
                   2959:     #thus invalidate the cache
                   2960:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 2961:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   2962:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 2963:     &Apache::lonnet::clear_EXT_cache_status();
                   2964: 
1.398     albertel 2965:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   2966:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       2967: 
                   2968:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 2969:     $result.=&jscriptNform($symb);
1.41      ng       2970: 
1.44      ng       2971:     #beginning of class grading form
1.41      ng       2972:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.106     albertel 2973: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.38      ng       2974: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.257     albertel 2975: 	'<input type="hidden" name="section" value="'.$env{'form.section'}.'" />'."\n".
                   2976: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   2977: 	'<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
                   2978: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       2979: 
1.126     ng       2980:     my $sectionClass;
1.257     albertel 2981:     if ($env{'form.section'} eq 'all') {
1.126     ng       2982: 	$sectionClass='Class </h3>';
1.257     albertel 2983:     } elsif ($env{'form.section'} eq 'none') {
1.126     ng       2984: 	$sectionClass='Students in no Section </h3>';
1.52      albertel 2985:     } else {
1.257     albertel 2986: 	$sectionClass='Students in Section '.$env{'form.section'}.'</h3>';
1.52      albertel 2987:     }
1.126     ng       2988:     $result.='<h3>Assign Common Grade To '.$sectionClass;
1.52      albertel 2989:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   2990: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       2991:     #radio buttons/text box for assigning points for a section or class.
                   2992:     #handles different parts of a problem
1.375     albertel 2993:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       2994:     my %weight = ();
                   2995:     my $ctsparts = 0;
1.41      ng       2996:     $result.='<table border="0">';
1.45      ng       2997:     my %seen = ();
1.375     albertel 2998:     my @part_response_id = &flatten_responseType($responseType);
                   2999:     foreach my $part_response_id (@part_response_id) {
                   3000:     	my ($partid,$respid) = @{ $part_response_id };
                   3001: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3002: 	next if $seen{$partid};
                   3003: 	$seen{$partid}++;
1.375     albertel 3004: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3005: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3006: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3007: 
1.44      ng       3008: 	$result.='<input type="hidden" name="partid_'.
                   3009: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3010: 	$result.='<input type="hidden" name="weight_'.
                   3011: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3012: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 3013: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3014: 	$result.='<table border="0"><tr>';  
1.41      ng       3015: 	my $ctr = 0;
1.42      ng       3016: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3017: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3018: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3019: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3020: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3021: 	    $ctr++;
                   3022: 	}
                   3023: 	$result.='</tr></table>';
1.44      ng       3024: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3025: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3026: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3027: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   3028: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3029: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3030: 		$weight{$partid}.')"> '.
1.42      ng       3031: 	    '<option selected="on"> </option>'.
1.125     ng       3032: 	    '<option>excused</option>'.
1.265     www      3033: 	    '<option>reset status</option></select></td>'.
1.266     albertel 3034:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       3035: 	$ctsparts++;
1.41      ng       3036:     }
1.52      albertel 3037:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   3038: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3039:     $result.='<input type="button" value="Revert to Default" '.
1.111     ng       3040: 	'onClick="javascript:resetEntry('.$ctsparts.');" TARGET=_self>';
1.41      ng       3041: 
1.44      ng       3042:     #table listing all the students in a section/class
                   3043:     #header of table
1.126     ng       3044:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       3045:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       3046: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       3047: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 3048:     my (@parts) = sort(&getpartlist($symb));
                   3049:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3050:     my @partids = ();
1.41      ng       3051:     foreach my $part (@parts) {
                   3052: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3053: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3054: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3055: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3056:         push(@partids, $partid);
1.324     albertel 3057: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3058: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 3059: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   3060: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       3061: 	    next;
1.207     albertel 3062: 	} else {
                   3063: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3064: 	}
1.53      albertel 3065: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 3066: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       3067:     }
                   3068:     $result.='</tr>';
1.44      ng       3069: 
1.270     albertel 3070:     my %last_resets = 
                   3071: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3072: 
1.41      ng       3073:     #get info for each student
1.44      ng       3074:     #list all the students - with points and grade status
1.257     albertel 3075:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3076:     my $ctr = 0;
1.294     albertel 3077:     foreach (sort 
                   3078: 	     {
                   3079: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3080: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3081: 		 }
                   3082: 		 return $a cmp $b;
                   3083: 	     } (keys(%$fullname))) {
1.126     ng       3084: 	$ctr++;
1.324     albertel 3085: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3086: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3087:     }
                   3088:     $result.='</table></td></tr></table>';
                   3089:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3090:     $result.='<input type="button" value="Save" '.
1.45      ng       3091: 	'onClick="javascript:submit();" TARGET=_self /></form>'."\n";
1.96      albertel 3092:     if (scalar(%$fullname) eq 0) {
                   3093: 	my $colspan=3+scalar(@parts);
1.398     albertel 3094: 	$result='<span class="LC_warning">There are no students in section "'.$env{'form.section'}.
                   3095: 	    '" with enrollment status "'.$env{'form.Status'}.'" to modify or grade.</span>';
1.96      albertel 3096:     }
1.324     albertel 3097:     $result.=&show_grading_menu_form($symb);
1.41      ng       3098:     return $result;
                   3099: }
                   3100: 
1.44      ng       3101: #--- call by previous routine to display each student
1.41      ng       3102: sub viewstudentgrade {
1.324     albertel 3103:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3104:     my ($uname,$udom) = split(/:/,$student);
                   3105:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3106:     my %aggregates = (); 
1.233     albertel 3107:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3108: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3109: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3110: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.112     ng       3111: 	'\')"; TARGET=_self>'.$fullname.'</a> '.
1.398     albertel 3112: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3113:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3114:     foreach my $apart (@$parts) {
                   3115: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3116: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3117:         $result.='<td align="center">';
1.269     raeburn  3118:         my ($aggtries,$totaltries);
                   3119:         unless (exists($aggregates{$part})) {
1.270     albertel 3120: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3121: 
                   3122: 	    $aggtries = $totaltries;
1.269     raeburn  3123:             if ($$last_resets{$part}) {  
1.270     albertel 3124:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3125: 					   $part);
                   3126:             }
1.269     raeburn  3127:             $result.='<input type="hidden" name="'.
                   3128:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3129:             $result.='<input type="hidden" name="'.
                   3130:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3131:             $aggregates{$part} = 1;
                   3132:         }
1.41      ng       3133: 	if ($type eq 'awarded') {
1.320     albertel 3134: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3135: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3136: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3137: 	    $result.='<input type="text" name="'.
1.89      albertel 3138: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3139: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3140: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3141: 	} elsif ($type eq 'solved') {
                   3142: 	    my ($status,$foo)=split(/_/,$score,2);
                   3143: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3144: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3145: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3146: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3147: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3148: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.125     ng       3149: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="on">excused</option>' 
                   3150: 		: '<option selected="on"> </option><option>excused</option>')."\n";
                   3151: 	    $result.='<option>reset status</option>';
1.126     ng       3152: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3153: 	} else {
                   3154: 	    $result.='<input type="hidden" name="'.
                   3155: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3156: 		    "\n";
1.233     albertel 3157: 	    $result.='<input type="text" name="'.
1.122     ng       3158: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3159: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3160: 	}
                   3161:     }
                   3162:     $result.='</tr>';
                   3163:     return $result;
1.38      ng       3164: }
                   3165: 
1.44      ng       3166: #--- change scores for all the students in a section/class
                   3167: #    record does not get update if unchanged
1.38      ng       3168: sub editgrades {
1.41      ng       3169:     my ($request) = @_;
                   3170: 
1.324     albertel 3171:     my $symb=&get_symb($request);
1.398     albertel 3172:     my $title='<h3><span class="LC_info">Current Grade Status</span></h3>';
                   3173:     $title.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4><br />'."\n";
                   3174:     $title.='<h4><b>Section: </b>'.$env{'form.section'}.'</h4>'."\n";
1.126     ng       3175: 
1.44      ng       3176:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3177:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3178: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3179: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3180: 
                   3181:     my %scoreptr = (
                   3182: 		    'correct'  =>'correct_by_override',
                   3183: 		    'incorrect'=>'incorrect_by_override',
                   3184: 		    'excused'  =>'excused',
                   3185: 		    'ungraded' =>'ungraded_attempted',
                   3186: 		    'nothing'  => '',
                   3187: 		    );
1.257     albertel 3188:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3189: 
1.44      ng       3190:     my (@partid);
                   3191:     my %weight = ();
1.54      albertel 3192:     my %columns = ();
1.44      ng       3193:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3194: 
1.324     albertel 3195:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3196:     my $header;
1.257     albertel 3197:     while ($ctr < $env{'form.totalparts'}) {
                   3198: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3199: 	push @partid,$partid;
1.257     albertel 3200: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3201: 	$ctr++;
1.54      albertel 3202:     }
1.324     albertel 3203:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3204:     foreach my $partid (@partid) {
                   3205: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3206: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3207: 	$columns{$partid}=2;
                   3208: 	foreach my $stores (@parts) {
                   3209: 	    my ($part,$type) = &split_part_type($stores);
                   3210: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3211: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3212: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3213: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3214: 	    $display =~ s/Number of Attempts/Tries/;
                   3215: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3216: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3217: 	    $columns{$partid}+=2;
                   3218: 	}
                   3219:     }
                   3220:     foreach my $partid (@partid) {
1.324     albertel 3221: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3222: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3223: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3224: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3225: 
1.44      ng       3226:     }
                   3227:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3228:     $result .= $header;
1.44      ng       3229:     $result .= '</tr>'."\n";
1.93      albertel 3230:     my $noupdate;
1.126     ng       3231:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3232:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3233: 	my $line;
1.257     albertel 3234: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3235: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3236: 	my %newrecord;
                   3237: 	my $updateflag = 0;
1.281     albertel 3238: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3239: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3240: 	if (!&canmodify($usec)) {
1.126     ng       3241: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3242: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3243: 	    next;
                   3244: 	}
1.269     raeburn  3245:         my %aggregate = ();
                   3246:         my $aggregateflag = 0;
1.281     albertel 3247: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3248: 	foreach (@partid) {
1.257     albertel 3249: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3250: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3251: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3252: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3253: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3254: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3255: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3256: 	    my $score;
                   3257: 	    if ($partial eq '') {
1.257     albertel 3258: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3259: 	    } elsif ($partial > 0) {
                   3260: 		$score = 'correct_by_override';
                   3261: 	    } elsif ($partial == 0) {
                   3262: 		$score = 'incorrect_by_override';
                   3263: 	    }
1.257     albertel 3264: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3265: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3266: 
1.292     albertel 3267: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3268: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3269: 	    if ($dropMenu eq 'reset status' &&
                   3270: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3271: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3272: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3273: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3274: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3275: 		$updateflag = 1;
1.269     raeburn  3276:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3277:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3278:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3279:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3280:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3281:                     $aggregateflag = 1;
                   3282:                 }
1.139     albertel 3283: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3284: 		$updateflag = 1;
                   3285: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3286: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3287: 		$rec_update++;
1.125     ng       3288: 	    }
                   3289: 
1.93      albertel 3290: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3291: 		'<td align="center">'.$awarded.
                   3292: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3293: 
1.54      albertel 3294: 
                   3295: 	    my $partid=$_;
                   3296: 	    foreach my $stores (@parts) {
                   3297: 		my ($part,$type) = &split_part_type($stores);
                   3298: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3299: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3300: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3301: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3302: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3303: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3304: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3305: 		    $updateflag=1;
                   3306: 		}
1.93      albertel 3307: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3308: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3309: 	    }
1.44      ng       3310: 	}
1.93      albertel 3311: 	$line.='</tr>'."\n";
1.301     albertel 3312: 
                   3313: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3314: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3315: 
1.44      ng       3316: 	if ($updateflag) {
                   3317: 	    $count++;
1.257     albertel 3318: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3319: 				    $udom,$uname);
1.301     albertel 3320: 
                   3321: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3322: 					      $cnum,$udom,$uname)) {
                   3323: 		# need to figure out if should be in queue.
                   3324: 		my %record =  
                   3325: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3326: 					     $udom,$uname);
                   3327: 		my $all_graded = 1;
                   3328: 		my $none_graded = 1;
                   3329: 		foreach my $part (@parts) {
                   3330: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3331: 			$all_graded = 0;
                   3332: 		    } else {
                   3333: 			$none_graded = 0;
                   3334: 		    }
                   3335: 		}
                   3336: 
                   3337: 		if ($all_graded || $none_graded) {
                   3338: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3339: 							   $symb,$cdom,$cnum,
                   3340: 							   $udom,$uname);
                   3341: 		}
                   3342: 	    }
                   3343: 
1.126     ng       3344: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3345: 	    $updateCtr++;
1.93      albertel 3346: 	} else {
1.126     ng       3347: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3348: 	    $noupdateCtr++;
1.44      ng       3349: 	}
1.269     raeburn  3350:         if ($aggregateflag) {
                   3351:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3352: 				  $cdom,$cnum);
1.269     raeburn  3353:         }
1.93      albertel 3354:     }
                   3355:     if ($noupdate) {
1.126     ng       3356: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3357: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3358: 	$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       3359:     }
1.72      ng       3360:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3361: 	&show_grading_menu_form ($symb);
1.125     ng       3362:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3363: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3364: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3365:     return $title.$msg.$result;
1.5       albertel 3366: }
1.54      albertel 3367: 
                   3368: sub split_part_type {
                   3369:     my ($partstr) = @_;
                   3370:     my ($temp,@allparts)=split(/_/,$partstr);
                   3371:     my $type=pop(@allparts);
                   3372:     my $part=join('.',@allparts);
                   3373:     return ($part,$type);
                   3374: }
                   3375: 
1.44      ng       3376: #------------- end of section for handling grading by section/class ---------
                   3377: #
                   3378: #----------------------------------------------------------------------------
                   3379: 
1.5       albertel 3380: 
1.44      ng       3381: #----------------------------------------------------------------------------
                   3382: #
                   3383: #-------------------------- Next few routines handles grading by csv upload
                   3384: #
                   3385: #--- Javascript to handle csv upload
1.27      albertel 3386: sub csvupload_javascript_reverse_associate {
1.246     albertel 3387:     my $error1=&mt('You need to specify the username or ID');
                   3388:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3389:   return(<<ENDPICK);
                   3390:   function verify(vf) {
                   3391:     var foundsomething=0;
                   3392:     var founduname=0;
1.243     albertel 3393:     var foundID=0;
1.27      albertel 3394:     for (i=0;i<=vf.nfields.value;i++) {
                   3395:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3396:       if (i==0 && tw!=0) { foundID=1; }
                   3397:       if (i==1 && tw!=0) { founduname=1; }
                   3398:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3399:     }
1.246     albertel 3400:     if (founduname==0 && foundID==0) {
                   3401: 	alert('$error1');
                   3402: 	return;
1.27      albertel 3403:     }
                   3404:     if (foundsomething==0) {
1.246     albertel 3405: 	alert('$error2');
                   3406: 	return;
1.27      albertel 3407:     }
                   3408:     vf.submit();
                   3409:   }
                   3410:   function flip(vf,tf) {
                   3411:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3412:     var i;
                   3413:     for (i=0;i<=vf.nfields.value;i++) {
                   3414:       //can not pick the same destination field for both name and domain
                   3415:       if (((i ==0)||(i ==1)) && 
                   3416:           ((tf==0)||(tf==1)) && 
                   3417:           (i!=tf) &&
                   3418:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3419:         eval('vf.f'+i+'.selectedIndex=0;')
                   3420:       }
                   3421:     }
                   3422:   }
                   3423: ENDPICK
                   3424: }
                   3425: 
                   3426: sub csvupload_javascript_forward_associate {
1.246     albertel 3427:     my $error1=&mt('You need to specify the username or ID');
                   3428:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3429:   return(<<ENDPICK);
                   3430:   function verify(vf) {
                   3431:     var foundsomething=0;
                   3432:     var founduname=0;
1.243     albertel 3433:     var foundID=0;
1.27      albertel 3434:     for (i=0;i<=vf.nfields.value;i++) {
                   3435:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3436:       if (tw==1) { foundID=1; }
                   3437:       if (tw==2) { founduname=1; }
                   3438:       if (tw>3) { foundsomething=1; }
1.27      albertel 3439:     }
1.246     albertel 3440:     if (founduname==0 && foundID==0) {
                   3441: 	alert('$error1');
                   3442: 	return;
1.27      albertel 3443:     }
                   3444:     if (foundsomething==0) {
1.246     albertel 3445: 	alert('$error2');
                   3446: 	return;
1.27      albertel 3447:     }
                   3448:     vf.submit();
                   3449:   }
                   3450:   function flip(vf,tf) {
                   3451:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3452:     var i;
                   3453:     //can not pick the same destination field twice
                   3454:     for (i=0;i<=vf.nfields.value;i++) {
                   3455:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3456:         eval('vf.f'+i+'.selectedIndex=0;')
                   3457:       }
                   3458:     }
                   3459:   }
                   3460: ENDPICK
                   3461: }
                   3462: 
1.26      albertel 3463: sub csvuploadmap_header {
1.324     albertel 3464:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3465:     my $javascript;
1.257     albertel 3466:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3467: 	$javascript=&csvupload_javascript_reverse_associate();
                   3468:     } else {
                   3469: 	$javascript=&csvupload_javascript_forward_associate();
                   3470:     }
1.45      ng       3471: 
1.324     albertel 3472:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3473:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3474:     my $ignore=&mt('Ignore First Line');
1.41      ng       3475:     $request->print(<<ENDPICK);
1.26      albertel 3476: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3477: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3478: $result
1.326     albertel 3479: <hr />
1.26      albertel 3480: <h3>Identify fields</h3>
                   3481: Total number of records found in file: $distotal <hr />
                   3482: Enter as many fields as you can. The system will inform you and bring you back
                   3483: to this page if the data selected is insufficient to run your class.<hr />
                   3484: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3485: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3486: <input type="hidden" name="associate"  value="" />
                   3487: <input type="hidden" name="phase"      value="three" />
                   3488: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3489: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3490: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3491: <input type="hidden" name="upfile_associate" 
1.257     albertel 3492:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3493: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3494: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3495: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3496: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3497: <hr />
                   3498: <script type="text/javascript" language="Javascript">
                   3499: $javascript
                   3500: </script>
                   3501: ENDPICK
1.118     ng       3502:     return '';
1.26      albertel 3503: 
                   3504: }
                   3505: 
                   3506: sub csvupload_fields {
1.324     albertel 3507:     my ($symb) = @_;
                   3508:     my (@parts) = &getpartlist($symb);
1.243     albertel 3509:     my @fields=(['ID','Student ID'],
                   3510: 		['username','Student Username'],
                   3511: 		['domain','Student Domain']);
1.324     albertel 3512:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3513:     foreach my $part (sort(@parts)) {
                   3514: 	my @datum;
                   3515: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3516: 	my $name=$part;
                   3517: 	if  (!$display) { $display = $name; }
                   3518: 	@datum=($name,$display);
1.244     albertel 3519: 	if ($name=~/^stores_(.*)_awarded/) {
                   3520: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3521: 	}
1.41      ng       3522: 	push(@fields,\@datum);
                   3523:     }
                   3524:     return (@fields);
1.26      albertel 3525: }
                   3526: 
                   3527: sub csvuploadmap_footer {
1.41      ng       3528:     my ($request,$i,$keyfields) =@_;
                   3529:     $request->print(<<ENDPICK);
1.26      albertel 3530: </table>
                   3531: <input type="hidden" name="nfields" value="$i" />
                   3532: <input type="hidden" name="keyfields" value="$keyfields" />
                   3533: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3534: </form>
                   3535: ENDPICK
                   3536: }
                   3537: 
1.283     albertel 3538: sub checkforfile_js {
1.86      ng       3539:     my $result =<<CSVFORMJS;
                   3540: <script type="text/javascript" language="javascript">
                   3541:     function checkUpload(formname) {
                   3542: 	if (formname.upfile.value == "") {
                   3543: 	    alert("Please use the browse button to select a file from your local directory.");
                   3544: 	    return false;
                   3545: 	}
                   3546: 	formname.submit();
                   3547:     }
                   3548:     </script>
                   3549: CSVFORMJS
1.283     albertel 3550:     return $result;
                   3551: }
                   3552: 
                   3553: sub upcsvScores_form {
                   3554:     my ($request) = shift;
1.324     albertel 3555:     my ($symb)=&get_symb($request);
1.283     albertel 3556:     if (!$symb) {return '';}
                   3557:     my $result=&checkforfile_js();
1.257     albertel 3558:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3559:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3560:     $result.=$table;
1.326     albertel 3561:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3562:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3563:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3564: 	'.</b></td></tr>'."\n";
                   3565:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3566:     my $upload=&mt("Upload Scores");
1.86      ng       3567:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3568:     my $ignore=&mt('Ignore First Line');
1.86      ng       3569:     $result.=<<ENDUPFORM;
1.106     albertel 3570: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3571: <input type="hidden" name="symb" value="$symb" />
                   3572: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3573: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3574: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3575: $upfile_select
1.370     www      3576: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3577: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3578: </form>
                   3579: ENDUPFORM
1.370     www      3580:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3581:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3582:     .'</td></tr></table>'."\n";
1.86      ng       3583:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3584:     $result.=&show_grading_menu_form($symb);
1.86      ng       3585:     return $result;
                   3586: }
                   3587: 
                   3588: 
1.26      albertel 3589: sub csvuploadmap {
1.41      ng       3590:     my ($request)= @_;
1.324     albertel 3591:     my ($symb)=&get_symb($request);
1.41      ng       3592:     if (!$symb) {return '';}
1.72      ng       3593: 
1.41      ng       3594:     my $datatoken;
1.257     albertel 3595:     if (!$env{'form.datatoken'}) {
1.41      ng       3596: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3597:     } else {
1.257     albertel 3598: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3599: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3600:     }
1.41      ng       3601:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3602:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3603:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3604:     my ($i,$keyfields);
                   3605:     if (@records) {
1.324     albertel 3606: 	my @fields=&csvupload_fields($symb);
1.45      ng       3607: 
1.257     albertel 3608: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3609: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3610: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3611: 							  \@fields);
                   3612: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3613: 	    chop($keyfields);
                   3614: 	} else {
                   3615: 	    unshift(@fields,['none','']);
                   3616: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3617: 							    \@fields);
1.311     banghart 3618:             foreach my $rec (@records) {
                   3619:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3620:                 if (%temp) {
                   3621:                     $keyfields=join(',',sort(keys(%temp)));
                   3622:                     last;
                   3623:                 }
                   3624:             }
1.41      ng       3625: 	}
                   3626:     }
                   3627:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3628:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3629: 
1.41      ng       3630:     return '';
1.27      albertel 3631: }
                   3632: 
1.246     albertel 3633: sub csvuploadoptions {
1.41      ng       3634:     my ($request)= @_;
1.324     albertel 3635:     my ($symb)=&get_symb($request);
1.257     albertel 3636:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3637:     my $ignore=&mt('Ignore First Line');
                   3638:     $request->print(<<ENDPICK);
                   3639: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3640: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3641: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3642: <!--
1.246     albertel 3643: <p>
                   3644: <label>
                   3645:    <input type="checkbox" name="show_full_results" />
                   3646:    Show a table of all changes
                   3647: </label>
                   3648: </p>
1.302     albertel 3649: -->
1.246     albertel 3650: <p>
                   3651: <label>
                   3652:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3653:    Overwrite any existing score
                   3654: </label>
                   3655: </p>
                   3656: ENDPICK
                   3657:     my %fields=&get_fields();
                   3658:     if (!defined($fields{'domain'})) {
1.257     albertel 3659: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3660: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3661:     }
1.257     albertel 3662:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3663: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3664: 	my $cleankey=$1;
                   3665: 	if ($cleankey eq 'command') { next; }
                   3666: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3667: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3668:     }
                   3669:     # FIXME do a check for any duplicated user ids...
                   3670:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3671:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3672: <hr /></form>'."\n");
1.324     albertel 3673:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3674:     return '';
                   3675: }
                   3676: 
                   3677: sub get_fields {
                   3678:     my %fields;
1.257     albertel 3679:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3680:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3681: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3682: 	    if ($env{'form.f'.$i} ne 'none') {
                   3683: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3684: 	    }
                   3685: 	} else {
1.257     albertel 3686: 	    if ($env{'form.f'.$i} ne 'none') {
                   3687: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3688: 	    }
                   3689: 	}
1.27      albertel 3690:     }
1.246     albertel 3691:     return %fields;
                   3692: }
                   3693: 
                   3694: sub csvuploadassign {
                   3695:     my ($request)= @_;
1.324     albertel 3696:     my ($symb)=&get_symb($request);
1.246     albertel 3697:     if (!$symb) {return '';}
1.345     bowersj2 3698:     my $error_msg = '';
1.246     albertel 3699:     &Apache::loncommon::load_tmp_file($request);
                   3700:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3701:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3702:     my %fields=&get_fields();
1.41      ng       3703:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3704:     my $courseid=$env{'request.course.id'};
1.97      albertel 3705:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3706:     my @notallowed;
1.41      ng       3707:     my @skipped;
                   3708:     my $countdone=0;
                   3709:     foreach my $grade (@gradedata) {
                   3710: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3711: 	my $domain;
                   3712: 	if ($entries{$fields{'domain'}}) {
                   3713: 	    $domain=$entries{$fields{'domain'}};
                   3714: 	} else {
1.257     albertel 3715: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3716: 	}
1.243     albertel 3717: 	$domain=~s/\s//g;
1.41      ng       3718: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3719: 	$username=~s/\s//g;
1.243     albertel 3720: 	if (!$username) {
                   3721: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3722: 	    $id=~s/\s//g;
1.243     albertel 3723: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3724: 	    $username=$ids{$id};
                   3725: 	}
1.41      ng       3726: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3727: 	    my $id=$entries{$fields{'ID'}};
                   3728: 	    $id=~s/\s//g;
                   3729: 	    if ($id) {
                   3730: 		push(@skipped,"$id:$domain");
                   3731: 	    } else {
                   3732: 		push(@skipped,"$username:$domain");
                   3733: 	    }
1.41      ng       3734: 	    next;
                   3735: 	}
1.108     albertel 3736: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3737: 	if (!&canmodify($usec)) {
                   3738: 	    push(@notallowed,"$username:$domain");
                   3739: 	    next;
                   3740: 	}
1.244     albertel 3741: 	my %points;
1.41      ng       3742: 	my %grades;
                   3743: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3744: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3745: 		$dest eq 'domain') { next; }
                   3746: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3747: 	    if ($dest=~/stores_(.*)_points/) {
                   3748: 		my $part=$1;
                   3749: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3750: 					      $symb,$domain,$username);
1.345     bowersj2 3751:                 if ($wgt) {
                   3752:                     $entries{$fields{$dest}}=~s/\s//g;
                   3753:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3754:                     my $award='correct_by_override';
                   3755:                     $grades{"resource.$part.awarded"}=$pcr;
                   3756:                     $grades{"resource.$part.solved"}=$award;
                   3757:                     $points{$part}=1;
                   3758:                 } else {
                   3759:                     $error_msg = "<br />" .
                   3760:                         &mt("Some point values were assigned"
                   3761:                             ." for problems with a weight "
                   3762:                             ."of zero. These values were "
                   3763:                             ."ignored.");
                   3764:                 }
1.244     albertel 3765: 	    } else {
                   3766: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3767: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3768: 		my $store_key=$dest;
                   3769: 		$store_key=~s/^stores/resource/;
                   3770: 		$store_key=~s/_/\./g;
                   3771: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3772: 	    }
1.41      ng       3773: 	}
1.398     albertel 3774: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3775: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.244     albertel 3776: #	&Apache::lonnet::logthis(" storing ".(join('-',%grades)));
1.302     albertel 3777: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3778: 					   $env{'request.course.id'},
                   3779: 					   $domain,$username);
                   3780: 	if ($result eq 'ok') {
                   3781: 	    $request->print('.');
                   3782: 	} else {
                   3783: 	    $request->print("<p>
1.398     albertel 3784:                               <span class=\"LC_error\">
                   3785:                                  Failed to save student $username:$domain.
                   3786:                                  Message when trying to save was ($result)
                   3787:                               </span>
1.302     albertel 3788:                              </p>" );
                   3789: 	}
1.41      ng       3790: 	$request->rflush();
                   3791: 	$countdone++;
                   3792:     }
1.398     albertel 3793:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3794:     if (@skipped) {
1.398     albertel 3795: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3796: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3797:     }
                   3798:     if (@notallowed) {
1.398     albertel 3799: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3800: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3801:     }
1.106     albertel 3802:     $request->print("<br />\n");
1.324     albertel 3803:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3804:     return $error_msg;
1.26      albertel 3805: }
1.44      ng       3806: #------------- end of section for handling csv file upload ---------
                   3807: #
                   3808: #-------------------------------------------------------------------
                   3809: #
1.122     ng       3810: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3811: #
                   3812: #--- Select a page/sequence and a student to grade
1.68      ng       3813: sub pickStudentPage {
                   3814:     my ($request) = shift;
                   3815: 
                   3816:     $request->print(<<LISTJAVASCRIPT);
                   3817: <script type="text/javascript" language="javascript">
                   3818: 
                   3819: function checkPickOne(formname) {
1.76      ng       3820:     if (radioSelection(formname.student) == null) {
1.68      ng       3821: 	alert("Please select the student you wish to grade.");
                   3822: 	return;
                   3823:     }
1.125     ng       3824:     ptr = pullDownSelection(formname.selectpage);
                   3825:     formname.page.value = formname["page"+ptr].value;
                   3826:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3827:     formname.submit();
                   3828: }
                   3829: 
                   3830: </script>
                   3831: LISTJAVASCRIPT
1.118     ng       3832:     &commonJSfunctions($request);
1.324     albertel 3833:     my ($symb) = &get_symb($request);
1.257     albertel 3834:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3835:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3836:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3837: 
1.398     albertel 3838:     my $result='<h3><span class="LC_info">&nbsp;'.
                   3839: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       3840: 
1.80      ng       3841:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3842:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.74      albertel 3843:     my ($titles,$symbx) = &getSymbMap($request);
1.137     albertel 3844:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3845: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3846: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3847:     my $ctr=0;
1.68      ng       3848:     foreach (@$titles) {
                   3849: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3850: 	$result.='<option value="'.$ctr.'" '.
1.71      ng       3851: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="on"' : '').
                   3852: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3853: 	$ctr++;
1.68      ng       3854:     }
1.326     albertel 3855:     $result.= '</select>'."<br />\n";
1.70      ng       3856:     $ctr=0;
                   3857:     foreach (@$titles) {
                   3858: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3859: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3860: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3861: 	$ctr++;
                   3862:     }
1.72      ng       3863:     $result.='<input type="hidden" name="page" />'."\n".
                   3864: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3865: 
1.288     albertel 3866:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="on" /> no </label>'."\n".
                   3867: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       3868: 
1.71      ng       3869:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 3870: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
                   3871: 	'<label><input type="radio" name="lastSub" value="datesub" checked /> by dates and submissions</label>'."\n".
                   3872: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.72      ng       3873: 
1.68      ng       3874:     $result.='<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
1.257     albertel 3875: 	'<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.72      ng       3876: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.80      ng       3877: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.257     albertel 3878: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       3879: 
1.382     albertel 3880:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   3881: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   3882: 
1.80      ng       3883:     $result.='&nbsp;<input type="button" '.
1.126     ng       3884: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       3885: 
1.68      ng       3886:     $request->print($result);
                   3887: 
1.326     albertel 3888:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       3889: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3890: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       3891: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3892: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       3893: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3894: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       3895:  
1.76      ng       3896:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       3897:     my $ptr = 1;
1.294     albertel 3898:     foreach my $student (sort 
                   3899: 			 {
                   3900: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3901: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3902: 			     }
                   3903: 			     return $a cmp $b;
                   3904: 			 } (keys(%$fullname))) {
1.68      ng       3905: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       3906: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   3907: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 3908: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   3909: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       3910: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       3911: 	$ptr++;
                   3912:     }
1.381     albertel 3913:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   3914:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       3915:     $studentTable.='<input type="button" '.
                   3916: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       3917: 
1.324     albertel 3918:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       3919:     $request->print($studentTable);
                   3920: 
                   3921:     return '';
                   3922: }
                   3923: 
                   3924: sub getSymbMap {
1.74      albertel 3925:     my ($request) = @_;
1.132     bowersj2 3926:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       3927: 
                   3928:     my %symbx = ();
                   3929:     my @titles = ();
1.117     bowersj2 3930:     my $minder = 0;
                   3931: 
                   3932:     # Gather every sequence that has problems.
1.240     albertel 3933:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   3934: 					       1,0,1);
1.117     bowersj2 3935:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 3936: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 3937: 	    my $title = $minder.'.'.
                   3938: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   3939: 	    push(@titles, $title); # minder in case two titles are identical
                   3940: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 3941: 	    $minder++;
1.241     albertel 3942: 	}
1.68      ng       3943:     }
                   3944:     return \@titles,\%symbx;
                   3945: }
                   3946: 
1.72      ng       3947: #
                   3948: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       3949: sub displayPage {
                   3950:     my ($request) = shift;
                   3951: 
1.324     albertel 3952:     my ($symb) = &get_symb($request);
1.257     albertel 3953:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3954:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3955:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3956:     my $pageTitle = $env{'form.page'};
1.103     albertel 3957:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 3958:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   3959:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 3960: 
                   3961:     #need to make sure we have the correct data for later EXT calls, 
                   3962:     #thus invalidate the cache
                   3963:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3964:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3965:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3966:     &Apache::lonnet::clear_EXT_cache_status();
                   3967: 
1.103     albertel 3968:     if (!&canview($usec)) {
1.398     albertel 3969: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 3970: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 3971: 	return;
                   3972:     }
1.398     albertel 3973:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 3974:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       3975: 	'</h3>'."\n";
1.382     albertel 3976:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   3977: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   3978:     } else {
                   3979: 	delete($env{'form.CODE'});
                   3980:     }
1.71      ng       3981:     &sub_page_js($request);
                   3982:     $request->print($result);
                   3983: 
1.132     bowersj2 3984:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 3985:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       3986:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 3987:     if (!$map) {
1.398     albertel 3988: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 3989: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 3990: 	return; 
                   3991:     }
1.68      ng       3992:     my $iterator = $navmap->getIterator($map->map_start(),
                   3993: 					$map->map_finish());
                   3994: 
1.71      ng       3995:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       3996: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 3997: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   3998: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       3999: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4000: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.72      ng       4001: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.125     ng       4002: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4003: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4004: 
1.382     albertel 4005:     if (defined($env{'form.CODE'})) {
                   4006: 	$studentTable.=
                   4007: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4008:     }
1.381     albertel 4009:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4010: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4011: 	'/check.gif" height="16" border="0" />';
                   4012: 
1.118     ng       4013:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4014: 	' symbol.'."\n".
1.71      ng       4015: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4016: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4017: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4018: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4019: 
1.329     albertel 4020:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4021:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4022:     $iterator->next(); # skip the first BEGIN_MAP
                   4023:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4024:     while ($depth > 0) {
1.68      ng       4025:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4026:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4027: 
1.385     albertel 4028:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4029: 	    my $parts = $curRes->parts();
1.68      ng       4030:             my $title = $curRes->compTitle();
1.71      ng       4031: 	    my $symbx = $curRes->symb();
1.196     albertel 4032: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4033: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4034: 	    $studentTable.='<td valign="top">';
1.382     albertel 4035: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4036: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4037: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4038: 					     undef,'both',\%form);
1.71      ng       4039: 	    } else {
1.382     albertel 4040: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4041: 		$companswer =~ s|<form(.*?)>||g;
                   4042: 		$companswer =~ s|</form>||g;
1.71      ng       4043: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4044: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4045: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4046: #		}
1.116     ng       4047: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4048: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4049: 	    }
                   4050: 
1.257     albertel 4051: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4052: 
1.257     albertel 4053: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4054: 		if ($record{'version'} eq '') {
1.398     albertel 4055: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4056: 		} else {
1.116     ng       4057: 		    my %responseType = ();
                   4058: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4059: 			my @responseIds =$curRes->responseIds($partid);
                   4060: 			my @responseType =$curRes->responseType($partid);
                   4061: 			my %responseIds;
                   4062: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4063: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4064: 			}
                   4065: 			$responseType{$partid} = \%responseIds;
1.116     ng       4066: 		    }
1.148     albertel 4067: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4068: 
1.71      ng       4069: 		}
1.257     albertel 4070: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4071: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4072: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4073: 									$env{'request.course.id'},
1.71      ng       4074: 									'','.submission');
                   4075:  
                   4076: 	    }
1.103     albertel 4077: 	    if (&canmodify($usec)) {
                   4078: 		foreach my $partid (@{$parts}) {
                   4079: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4080: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4081: 		    $question++;
                   4082: 		}
1.196     albertel 4083: 		$prob++;
1.71      ng       4084: 	    }
                   4085: 	    $studentTable.='</td></tr>';
1.68      ng       4086: 
1.103     albertel 4087: 	}
1.68      ng       4088:         $curRes = $iterator->next();
                   4089:     }
                   4090: 
1.381     albertel 4091:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4092: 	'<input type="button" value="Save" '.
1.381     albertel 4093: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4094: 	'</form>'."\n";
1.324     albertel 4095:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4096:     $request->print($studentTable);
                   4097: 
                   4098:     return '';
1.119     ng       4099: }
                   4100: 
                   4101: sub displaySubByDates {
1.148     albertel 4102:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4103:     my $isCODE=0;
1.335     albertel 4104:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4105:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4106:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4107: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4108: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4109: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4110: 	'<td><b>Submission</b></td>'.
                   4111: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4112:     my ($version);
                   4113:     my %mark;
1.148     albertel 4114:     my %orders;
1.119     ng       4115:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4116:     if (!exists($$record{'1:timestamp'})) {
1.398     albertel 4117: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
1.147     albertel 4118:     }
1.335     albertel 4119: 
                   4120:     my $interaction;
1.119     ng       4121:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4122: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4123: 	if (exists($$record{$version.':resource.0.version'})) {
                   4124: 	    $interaction = $$record{$version.':resource.0.version'};
                   4125: 	}
                   4126: 
                   4127: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4128: 		             : "$version:resource");
                   4129: 	#&Apache::lonnet::logthis(" got $where");
1.119     ng       4130: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4131: 	if ($isCODE) {
                   4132: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4133: 	}
1.119     ng       4134: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4135: 	my @displaySub = ();
                   4136: 	foreach my $partid (@{$parts}) {
1.335     albertel 4137: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4138: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4139: 	    
                   4140: 
1.122     ng       4141: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4142: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4143: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4144: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4145: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4146: 
                   4147: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4148: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   4149: 		    #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
1.207     albertel 4150: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.398     albertel 4151: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
                   4152: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4153: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4154: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4155: 		    } else {
                   4156: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4157: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4158: 		    }
1.335     albertel 4159: 		    my $responseType=($isTask ? 'Task'
                   4160:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4161: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4162: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4163: 			$orders{$partid}->{$responseId}=
                   4164: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4165: 		    }
1.147     albertel 4166: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4167: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4168: 		}
                   4169: 	    }
1.335     albertel 4170: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4171: 		$displaySub[1].='Checked in by '.
                   4172: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4173: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4174: 		    '<br />';
                   4175: 	    }
                   4176: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4177: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4178: 		    lc($$record{"$where.$partid.award"}).' '.
                   4179: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4180: 		    '<br />';
                   4181: 	    }
1.335     albertel 4182: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4183: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4184: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4185: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4186: 		$displaySub[2].=
                   4187: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4188: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4189: 	    }
                   4190: 	}
                   4191: 	# needed because old essay regrader has not parts info
                   4192: 	if (exists $$record{"$version:resource.regrader"}) {
                   4193: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4194: 	}
                   4195: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4196: 	if ($displaySub[2]) {
                   4197: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4198: 	}
1.382     albertel 4199: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4200:     
1.119     ng       4201:     }
                   4202:     $studentTable.='</table></td></tr></table>';
                   4203:     return $studentTable;
1.71      ng       4204: }
                   4205: 
                   4206: sub updateGradeByPage {
                   4207:     my ($request) = shift;
                   4208: 
1.257     albertel 4209:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4210:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4211:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4212:     my $pageTitle = $env{'form.page'};
1.103     albertel 4213:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4214:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4215:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4216:     if (!&canmodify($usec)) {
1.398     albertel 4217: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4218: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4219: 	return;
                   4220:     }
1.398     albertel 4221:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4222:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4223: 	'</h3>'."\n";
1.70      ng       4224: 
1.68      ng       4225:     $request->print($result);
                   4226: 
1.132     bowersj2 4227:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4228:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4229:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4230:     if (!$map) {
1.398     albertel 4231: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4232: 	my ($symb)=&get_symb($request);
                   4233: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4234: 	return; 
                   4235:     }
1.71      ng       4236:     my $iterator = $navmap->getIterator($map->map_start(),
                   4237: 					$map->map_finish());
1.70      ng       4238: 
1.71      ng       4239:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4240: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4241: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4242: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4243: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4244: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4245: 
                   4246:     $iterator->next(); # skip the first BEGIN_MAP
                   4247:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4248:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4249:     while ($depth > 0) {
1.71      ng       4250:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4251:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4252: 
1.385     albertel 4253:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4254: 	    my $parts = $curRes->parts();
1.71      ng       4255:             my $title = $curRes->compTitle();
                   4256: 	    my $symbx = $curRes->symb();
1.196     albertel 4257: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4258: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4259: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4260: 
                   4261: 	    my %newrecord=();
                   4262: 	    my @displayPts=();
1.269     raeburn  4263:             my %aggregate = ();
                   4264:             my $aggregateflag = 0;
1.71      ng       4265: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4266: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4267: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4268: 
1.257     albertel 4269: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4270: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4271: 		my $partial = $newpts/$wgt;
                   4272: 		my $score;
                   4273: 		if ($partial > 0) {
                   4274: 		    $score = 'correct_by_override';
1.125     ng       4275: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4276: 		    $score = 'incorrect_by_override';
                   4277: 		}
1.257     albertel 4278: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4279: 		if ($dropMenu eq 'excused') {
1.71      ng       4280: 		    $partial = '';
                   4281: 		    $score = 'excused';
1.125     ng       4282: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4283: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4284: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4285: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4286: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4287: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4288: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4289: 		    $changeflag++;
                   4290: 		    $newpts = '';
1.269     raeburn  4291:                     
                   4292:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4293:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4294:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4295:                     if ($aggtries > 0) {
                   4296:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4297:                         $aggregateflag = 1;
                   4298:                     }
1.71      ng       4299: 		}
1.324     albertel 4300: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4301: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4302: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4303: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4304: 		    '&nbsp;<br />';
1.207     albertel 4305: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4306: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4307: 		    '&nbsp;<br />';
1.71      ng       4308: 		$question++;
1.380     albertel 4309: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4310: 
1.71      ng       4311: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4312: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4313: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4314: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4315: 
                   4316: 		$changeflag++;
                   4317: 	    }
                   4318: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4319: 		my %record = 
                   4320: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4321: 					     $udom,$uname);
                   4322: 
                   4323: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4324: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4325: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4326: 		    $newrecord{'resource.CODE'} = '';
                   4327: 		}
1.257     albertel 4328: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4329: 					$udom,$uname);
1.382     albertel 4330: 		%record = &Apache::lonnet::restore($symbx,
                   4331: 						   $env{'request.course.id'},
                   4332: 						   $udom,$uname);
1.380     albertel 4333: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4334: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4335: 	    }
1.380     albertel 4336: 	    
1.269     raeburn  4337:             if ($aggregateflag) {
                   4338:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4339:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4340:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4341:             }
1.125     ng       4342: 
1.71      ng       4343: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4344: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4345: 		'</tr>';
1.68      ng       4346: 
1.196     albertel 4347: 	    $prob++;
1.68      ng       4348: 	}
1.71      ng       4349:         $curRes = $iterator->next();
1.68      ng       4350:     }
1.98      albertel 4351: 
1.71      ng       4352:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4353:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4354:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4355: 		  'The scores were changed for '.
                   4356: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4357:     $request->print($grademsg.$studentTable);
1.68      ng       4358: 
1.70      ng       4359:     return '';
                   4360: }
                   4361: 
1.72      ng       4362: #-------- end of section for handling grading by page/sequence ---------
                   4363: #
                   4364: #-------------------------------------------------------------------
                   4365: 
1.75      albertel 4366: #--------------------Scantron Grading-----------------------------------
                   4367: #
                   4368: #------ start of section for handling grading by page/sequence ---------
                   4369: 
1.81      albertel 4370: sub defaultFormData {
1.324     albertel 4371:     my ($symb)=@_;
1.81      albertel 4372:     return '
                   4373:       <input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.257     albertel 4374:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4375:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4376: }
                   4377: 
1.75      albertel 4378: sub getSequenceDropDown {
                   4379:     my ($request,$symb)=@_;
                   4380:     my $result='<select name="selectpage">'."\n";
                   4381:     my ($titles,$symbx) = &getSymbMap($request);
1.137     albertel 4382:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4383:     my $ctr=0;
                   4384:     foreach (@$titles) {
                   4385: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4386: 	$result.='<option value="'.$$symbx{$_}.'" '.
                   4387: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="on"' : '').
                   4388: 	    '>'.$showtitle.'</option>'."\n";
                   4389: 	$ctr++;
                   4390:     }
                   4391:     $result.= '</select>';
                   4392:     return $result;
                   4393: }
                   4394: 
1.202     albertel 4395: sub scantron_filenames {
1.257     albertel 4396:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4397:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4398:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4399: 				    &propath($cdom,$cname));
1.202     albertel 4400:     my @possiblenames;
1.201     albertel 4401:     foreach my $filename (sort(@files)) {
1.157     albertel 4402: 	($filename)=split(/&/,$filename);
                   4403: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4404: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4405: 	push(@possiblenames,$filename);
                   4406:     }
                   4407:     return @possiblenames;
                   4408: }
                   4409: 
                   4410: sub scantron_uploads {
1.209     ng       4411:     my ($file2grade) = @_;
1.202     albertel 4412:     my $result=	'<select name="scantron_selectfile">';
                   4413:     $result.="<option></option>";
                   4414:     foreach my $filename (sort(&scantron_filenames())) {
1.209     ng       4415: 	$result.="<option".($filename eq $file2grade ? ' selected="on"':'').">$filename</option>\n";
1.81      albertel 4416:     }
                   4417:     $result.="</select>";
                   4418:     return $result;
                   4419: }
                   4420: 
1.82      albertel 4421: sub scantron_scantab {
                   4422:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4423:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4424:     $result.='<option></option>'."\n";
1.82      albertel 4425:     foreach my $line (<$fh>) {
                   4426: 	my ($name,$descrip)=split(/:/,$line);
                   4427: 	if ($name =~ /^\#/) { next; }
                   4428: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4429:     }
                   4430:     $result.='</select>'."\n";
                   4431: 
                   4432:     return $result;
                   4433: }
                   4434: 
1.186     albertel 4435: sub scantron_CODElist {
1.257     albertel 4436:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4437:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4438:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4439:     my $namechoice='<option></option>';
1.225     albertel 4440:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4441: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4442: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4443: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4444:     }
                   4445:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4446:     return $namechoice;
                   4447: }
                   4448: 
                   4449: sub scantron_CODEunique {
1.381     albertel 4450:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4451:                  <label><input type="radio" name="scantron_CODEunique"
1.308     albertel 4452:                         value="yes" checked="checked" /> Yes </label>
1.381     albertel 4453:                 </span>
                   4454:                 <span style="white-space: nowrap;">
1.272     albertel 4455:                  <label><input type="radio" name="scantron_CODEunique"
1.308     albertel 4456:                         value="no" /> No </label>
1.381     albertel 4457:                 </span>';
1.186     albertel 4458:     return $result;
                   4459: }
                   4460: 
1.75      albertel 4461: sub scantron_selectphase {
1.209     ng       4462:     my ($r,$file2grade) = @_;
1.324     albertel 4463:     my ($symb)=&get_symb($r);
1.75      albertel 4464:     if (!$symb) {return '';}
                   4465:     my $sequence_selector=&getSequenceDropDown($r,$symb);
1.324     albertel 4466:     my $default_form_data=&defaultFormData($symb);
                   4467:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4468:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4469:     my $format_selector=&scantron_scantab();
1.186     albertel 4470:     my $CODE_selector=&scantron_CODElist();
                   4471:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4472:     my $result;
1.157     albertel 4473:     #FIXME allow instructor to be able to download the scantron file
                   4474:     # and to upload it,
1.75      albertel 4475:     $result.= <<SCANTRONFORM;
1.162     albertel 4476:     <table width="100%" border="0">
1.75      albertel 4477:     <tr>
1.226     albertel 4478:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4479:       <td bgcolor="#777777">
1.203     albertel 4480:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4481:         $default_form_data
1.75      albertel 4482:         <table width="100%" border="0">
                   4483:           <tr bgcolor="#e6ffff">
1.174     albertel 4484:             <td colspan="2">
                   4485:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4486:             </td>
                   4487:           </tr>
                   4488:           <tr bgcolor="#ffffe6">
1.174     albertel 4489:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4490:           </tr>
                   4491:           <tr bgcolor="#ffffe6">
1.174     albertel 4492:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4493:           </tr>
1.82      albertel 4494:           <tr bgcolor="#ffffe6">
1.174     albertel 4495:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4496:           </tr>
1.157     albertel 4497:           <tr bgcolor="#ffffe6">
1.186     albertel 4498:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4499:           </tr>
                   4500:           <tr bgcolor="#ffffe6">
                   4501:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4502:           </tr>
                   4503:           <tr bgcolor="#ffffe6">
1.187     albertel 4504: 	    <td> Options: </td>
                   4505:             <td>
1.272     albertel 4506: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.331     albertel 4507:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all exisiting corrections</label> <br />
                   4508:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4509: 	    </td>
                   4510:           </tr>
                   4511:           <tr bgcolor="#ffffe6">
1.174     albertel 4512:             <td colspan="2">
1.265     www      4513:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4514:             </td>
                   4515:           </tr>
                   4516:         </table>
1.226     albertel 4517:        </td>
                   4518:      </form>
1.162     albertel 4519:     </tr>
                   4520: SCANTRONFORM
                   4521:    
                   4522:     $r->print($result);
                   4523: 
1.257     albertel 4524:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4525:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4526: 
                   4527:         $r->print(<<SCANTRONFORM);
                   4528:     <tr>
                   4529:       <td bgcolor="#777777">
                   4530:         <table width="100%" border="0">
                   4531:           <tr bgcolor="#e6ffff">
                   4532:             <td>
1.174     albertel 4533:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4534:             </td>
                   4535:           </tr>
                   4536:           <tr bgcolor="#ffffe6">
                   4537:             <td>
                   4538: SCANTRONFORM
1.324     albertel 4539:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4540:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4541:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4542:     $r->print(<<UPLOAD);
                   4543:               <script type="text/javascript" language="javascript">
                   4544:     function checkUpload(formname) {
                   4545: 	if (formname.upfile.value == "") {
                   4546: 	    alert("Please use the browse button to select a file from your local directory.");
                   4547: 	    return false;
                   4548: 	}
                   4549: 	formname.submit();
                   4550:     }
                   4551:               </script>
                   4552: 
                   4553:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4554:                 $default_form_data
                   4555:                 <input name='courseid' type='hidden' value='$cnum' />
                   4556:                 <input name='domainid' type='hidden' value='$cdom' />
                   4557:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4558:                 File to upload:<input type="file" name="upfile" size="50" />
                   4559:                 <br />
                   4560:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4561:               </form>
                   4562: UPLOAD
1.162     albertel 4563: 
                   4564:         $r->print(<<SCANTRONFORM);
                   4565:             </td>
                   4566:           </tr>
1.75      albertel 4567:         </table>
                   4568:       </td>
                   4569:     </tr>
1.162     albertel 4570: SCANTRONFORM
                   4571:     }
1.187     albertel 4572:     $r->print(<<SCANTRONFORM);
                   4573:     <tr>
1.226     albertel 4574:       <form action='/adm/grades' name='scantron_download'>
                   4575:         <td bgcolor="#777777">
1.379     albertel 4576: 	  $default_form_data
1.187     albertel 4577:           <input type="hidden" name="command" value="scantron_download" />
                   4578:           <table width="100%" border="0">
                   4579:             <tr bgcolor="#e6ffff">
                   4580:               <td colspan="2">
                   4581:                 &nbsp;<b>Download a scoring office file</b>
                   4582:               </td>
                   4583:             </tr>
                   4584:             <tr bgcolor="#ffffe6">
                   4585:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4586:             </tr>
                   4587:             <tr bgcolor="#ffffe6">
                   4588:               <td colspan="2">
1.293     www      4589:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4590:               </td>
                   4591:             </tr>
                   4592:           </table>
1.226     albertel 4593:         </td>
                   4594:       </form>
1.187     albertel 4595:     </tr>
                   4596: SCANTRONFORM
1.162     albertel 4597: 
                   4598:     $r->print(<<SCANTRONFORM);
1.75      albertel 4599:   </table>
1.81      albertel 4600: $grading_menu_button
1.75      albertel 4601: SCANTRONFORM
                   4602: 
1.162     albertel 4603:     return
1.75      albertel 4604: }
                   4605: 
1.82      albertel 4606: sub get_scantron_config {
                   4607:     my ($which) = @_;
                   4608:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4609:     my %config;
1.157     albertel 4610:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4611:     foreach my $line (<$fh>) {
                   4612: 	my ($name,$descrip)=split(/:/,$line);
                   4613: 	if ($name ne $which ) { next; }
                   4614: 	chomp($line);
                   4615: 	my @config=split(/:/,$line);
                   4616: 	$config{'name'}=$config[0];
                   4617: 	$config{'description'}=$config[1];
                   4618: 	$config{'CODElocation'}=$config[2];
                   4619: 	$config{'CODEstart'}=$config[3];
                   4620: 	$config{'CODElength'}=$config[4];
                   4621: 	$config{'IDstart'}=$config[5];
                   4622: 	$config{'IDlength'}=$config[6];
                   4623: 	$config{'Qstart'}=$config[7];
                   4624: 	$config{'Qlength'}=$config[8];
                   4625: 	$config{'Qoff'}=$config[9];
                   4626: 	$config{'Qon'}=$config[10];
1.157     albertel 4627: 	$config{'PaperID'}=$config[11];
                   4628: 	$config{'PaperIDlength'}=$config[12];
                   4629: 	$config{'FirstName'}=$config[13];
                   4630: 	$config{'FirstNamelength'}=$config[14];
                   4631: 	$config{'LastName'}=$config[15];
                   4632: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4633: 	last;
                   4634:     }
                   4635:     return %config;
                   4636: }
                   4637: 
                   4638: sub username_to_idmap {
                   4639:     my ($classlist)= @_;
                   4640:     my %idmap;
                   4641:     foreach my $student (keys(%$classlist)) {
                   4642: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4643: 	    $student;
                   4644:     }
                   4645:     return %idmap;
                   4646: }
                   4647: 
1.157     albertel 4648: sub scantron_fixup_scanline {
                   4649:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   4650:     if ($field eq 'ID') {
                   4651: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 4652: 	    return ($line,1,'New value too large');
1.157     albertel 4653: 	}
                   4654: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   4655: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   4656: 				     $args->{'newid'});
                   4657: 	}
                   4658: 	substr($line,$$scantron_config{'IDstart'}-1,
                   4659: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   4660: 	if ($args->{'newid'}=~/^\s*$/) {
                   4661: 	    &scan_data($scan_data,"$whichline.user",
                   4662: 		       $args->{'username'}.':'.$args->{'domain'});
                   4663: 	}
1.186     albertel 4664:     } elsif ($field eq 'CODE') {
1.192     albertel 4665: 	if ($args->{'CODE_ignore_dup'}) {
                   4666: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   4667: 	}
                   4668: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   4669: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 4670: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   4671: 		return ($line,1,'New CODE value too large');
                   4672: 	    }
                   4673: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   4674: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   4675: 	    }
                   4676: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   4677: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 4678: 	}
1.157     albertel 4679:     } elsif ($field eq 'answer') {
                   4680: 	my $length=$scantron_config->{'Qlength'};
                   4681: 	my $off=$scantron_config->{'Qoff'};
                   4682: 	my $on=$scantron_config->{'Qon'};
                   4683: 	my $answer=${off}x$length;
                   4684: 	if ($args->{'response'} eq 'none') {
                   4685: 	    &scan_data($scan_data,
                   4686: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   4687: 	} else {
1.274     albertel 4688: 	    if ($on eq 'letter') {
                   4689: 		my @alphabet=('A'..'Z');
                   4690: 		$answer=$alphabet[$args->{'response'}];
                   4691: 	    } elsif ($on eq 'number') {
                   4692: 		$answer=$args->{'response'}+1;
1.389     albertel 4693: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 4694: 	    } else {
                   4695: 		substr($answer,$args->{'response'},1)=$on;
                   4696: 	    }
1.157     albertel 4697: 	    &scan_data($scan_data,
                   4698: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   4699: 	}
                   4700: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   4701: 	substr($line,$where-1,$length)=$answer;
                   4702:     }
                   4703:     return $line;
                   4704: }
                   4705: 
                   4706: sub scan_data {
                   4707:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 4708:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 4709:     if (defined($value)) {
                   4710: 	$scan_data->{$filename.'_'.$key} = $value;
                   4711:     }
                   4712:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   4713:     return $scan_data->{$filename.'_'.$key};
                   4714: }
                   4715: 
1.82      albertel 4716: sub scantron_parse_scanline {
1.194     albertel 4717:     my ($line,$whichline,$scantron_config,$scan_data,$justHeader)=@_;
1.82      albertel 4718:     my %record;
                   4719:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);
                   4720:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);
1.278     albertel 4721:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   4722: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   4723: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   4724: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   4725: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 4726: 	    $record{'scantron.CODE'}=substr($data,
                   4727: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 4728: 					    $$scantron_config{'CODElength'});
1.191     albertel 4729: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   4730: 		$record{'scantron.useCODE'}=1;
                   4731: 	    }
1.192     albertel 4732: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   4733: 		$record{'scantron.CODE_ignore_dup'}=1;
                   4734: 	    }
1.82      albertel 4735: 	} else {
                   4736: 	    #FIXME interpret first N questions
                   4737: 	}
                   4738:     }
1.83      albertel 4739:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   4740: 				  $$scantron_config{'IDlength'});
1.157     albertel 4741:     $record{'scantron.PaperID'}=
                   4742: 	substr($data,$$scantron_config{'PaperID'}-1,
                   4743: 	       $$scantron_config{'PaperIDlength'});
                   4744:     $record{'scantron.FirstName'}=
                   4745: 	substr($data,$$scantron_config{'FirstName'}-1,
                   4746: 	       $$scantron_config{'FirstNamelength'});
                   4747:     $record{'scantron.LastName'}=
                   4748: 	substr($data,$$scantron_config{'LastName'}-1,
                   4749: 	       $$scantron_config{'LastNamelength'});
1.194     albertel 4750:     if ($justHeader) { return \%record; }
                   4751: 
1.82      albertel 4752:     my @alphabet=('A'..'Z');
                   4753:     my $questnum=0;
                   4754:     while ($questions) {
                   4755: 	$questnum++;
                   4756: 	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
                   4757: 	substr($questions,0,$$scantron_config{'Qlength'})='';
1.83      albertel 4758: 	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
1.239     albertel 4759: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.371     albertel 4760: 	    if ($currentquest eq '?'
                   4761: 		|| $currentquest eq '*') {
1.274     albertel 4762: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4763: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 4764: 	    } elsif (!defined($currentquest)
1.274     albertel 4765: 		     || $currentquest eq $$scantron_config{'Qoff'}
                   4766: 		     || $currentquest !~ /^[A-Z]$/) {
1.239     albertel 4767: 		$record{"scantron.$questnum.answer"}='';
                   4768: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4769: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4770: 		}
                   4771: 	    } else {
                   4772: 		$record{"scantron.$questnum.answer"}=$currentquest;
                   4773: 	    }
                   4774: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.371     albertel 4775: 	    if ($currentquest eq '?'
                   4776: 		|| $currentquest eq '*') {
1.274     albertel 4777: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4778: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 4779: 	    } elsif (!defined($currentquest)
                   4780: 		     || $currentquest eq $$scantron_config{'Qoff'} 
                   4781: 		     || $currentquest !~ /^\d$/) {
1.239     albertel 4782: 		$record{"scantron.$questnum.answer"}='';
                   4783: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4784: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4785: 		}
                   4786: 	    } else {
1.371     albertel 4787: 		# wrap zero back to J
                   4788: 		if ($currentquest eq '0') {
                   4789: 		    $record{"scantron.$questnum.answer"}=
                   4790: 			$alphabet[9];
                   4791: 		} else {
                   4792: 		    $record{"scantron.$questnum.answer"}=
                   4793: 			$alphabet[$currentquest-1];
                   4794: 		}
1.239     albertel 4795: 	    }
1.82      albertel 4796: 	} else {
1.239     albertel 4797: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
                   4798: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}) {
                   4799: 		$record{"scantron.$questnum.answer"}='';
                   4800: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4801: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4802: 		}
                   4803: 	    } else {
                   4804: 		$record{"scantron.$questnum.answer"}=
                   4805: 		    $alphabet[length($array[0])];
                   4806: 	    }
                   4807: 	    if (scalar(@array) gt 2) {
                   4808: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4809: 		my @ans=@array;
                   4810: 		my $i=length($ans[0]);shift(@ans);
                   4811: 		while ($#ans) {
                   4812: 		    $i+=length($ans[0])+1;
                   4813: 		    $record{"scantron.$questnum.answer"}.=$alphabet[$i];
                   4814: 		    shift(@ans);
                   4815: 		}
                   4816: 	    }
1.82      albertel 4817: 	}
                   4818:     }
1.83      albertel 4819:     $record{'scantron.maxquest'}=$questnum;
                   4820:     return \%record;
1.82      albertel 4821: }
                   4822: 
                   4823: sub scantron_add_delay {
1.140     albertel 4824:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   4825:     push(@$delayqueue,
                   4826: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   4827: 	  'ecode' => $errorcode }
                   4828: 	 );
1.82      albertel 4829: }
                   4830: 
                   4831: sub scantron_find_student {
1.157     albertel 4832:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 4833:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 4834:     if ($scanID =~ /^\s*$/) {
                   4835:  	return &scan_data($scan_data,"$line.user");
                   4836:     }
1.83      albertel 4837:     foreach my $id (keys(%$idmap)) {
1.157     albertel 4838:  	if (lc($id) eq lc($scanID)) {
                   4839:  	    return $$idmap{$id};
                   4840:  	}
1.83      albertel 4841:     }
                   4842:     return undef;
                   4843: }
                   4844: 
                   4845: sub scantron_filter {
                   4846:     my ($curres)=@_;
1.331     albertel 4847: 
                   4848:     if (ref($curres) && $curres->is_problem()) {
                   4849: 	# if the user has asked to not have either hidden
                   4850: 	# or 'randomout' controlled resources to be graded
                   4851: 	# don't include them
                   4852: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   4853: 	    && $curres->randomout) {
                   4854: 	    return 0;
                   4855: 	}
1.83      albertel 4856: 	return 1;
                   4857:     }
                   4858:     return 0;
1.82      albertel 4859: }
                   4860: 
1.157     albertel 4861: sub scantron_process_corrections {
                   4862:     my ($r) = @_;
1.257     albertel 4863:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 4864:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4865:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 4866:     my $which=$env{'form.scantron_line'};
1.200     albertel 4867:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 4868:     my ($skip,$err,$errmsg);
1.257     albertel 4869:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 4870: 	$skip=1;
1.257     albertel 4871:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   4872: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   4873: 	    $env{'form.scantron_domain'};
1.157     albertel 4874: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   4875: 	($line,$err,$errmsg)=
                   4876: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   4877: 				     'ID',{'newid'=>$newid,
1.257     albertel 4878: 				    'username'=>$env{'form.scantron_username'},
                   4879: 				    'domain'=>$env{'form.scantron_domain'}});
                   4880:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   4881: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 4882: 	my $newCODE;
1.192     albertel 4883: 	my %args;
1.190     albertel 4884: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 4885: 	    $newCODE='use_unfound';
1.190     albertel 4886: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 4887: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 4888: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 4889: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 4890: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 4891: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 4892: 	}
1.257     albertel 4893: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 4894: 	    $args{'CODE_ignore_dup'}=1;
                   4895: 	}
                   4896: 	$args{'CODE'}=$newCODE;
1.186     albertel 4897: 	($line,$err,$errmsg)=
                   4898: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 4899: 				     'CODE',\%args);
1.257     albertel 4900:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   4901: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 4902: 	    ($line,$err,$errmsg)=
                   4903: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   4904: 					 $which,'answer',
                   4905: 					 { 'question'=>$question,
1.257     albertel 4906: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 4907: 	    if ($err) { last; }
                   4908: 	}
                   4909:     }
                   4910:     if ($err) {
1.398     albertel 4911: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 4912:     } else {
1.200     albertel 4913: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 4914: 	&scantron_putfile($scanlines,$scan_data);
                   4915:     }
                   4916: }
                   4917: 
1.200     albertel 4918: sub reset_skipping_status {
                   4919:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4920:     &scan_data($scan_data,'remember_skipping',undef,1);
                   4921:     &scantron_putfile(undef,$scan_data);
                   4922: }
                   4923: 
1.376     albertel 4924: sub start_skipping {
1.200     albertel 4925:     my ($scan_data,$i)=@_;
                   4926:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 4927:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   4928: 	$remembered{$i}=2;
                   4929:     } else {
                   4930: 	$remembered{$i}=1;
                   4931:     }
1.200     albertel 4932:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   4933: }
                   4934: 
                   4935: sub should_be_skipped {
1.376     albertel 4936:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 4937:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 4938: 	# not redoing old skips
1.376     albertel 4939: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 4940: 	return 0;
                   4941:     }
                   4942:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 4943: 
                   4944:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   4945: 	return 0;
                   4946:     }
1.200     albertel 4947:     return 1;
                   4948: }
                   4949: 
                   4950: sub remember_current_skipped {
                   4951:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4952:     my %to_remember;
                   4953:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   4954: 	if ($scanlines->{'skipped'}[$i]) {
                   4955: 	    $to_remember{$i}=1;
                   4956: 	}
                   4957:     }
1.376     albertel 4958: 
1.200     albertel 4959:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   4960:     &scantron_putfile(undef,$scan_data);
                   4961: }
                   4962: 
                   4963: sub check_for_error {
                   4964:     my ($r,$result)=@_;
                   4965:     if ($result ne 'ok' && $result ne 'not_found' ) {
                   4966: 	$r->print("An error occured ($result) when trying to Remove the existing corrections.");
                   4967:     }
                   4968: }
1.157     albertel 4969: 
1.203     albertel 4970: sub scantron_warning_screen {
                   4971:     my ($button_text)=@_;
1.257     albertel 4972:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 4973:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 4974:     my $CODElist;
1.284     albertel 4975:     if ($scantron_config{'CODElocation'} &&
                   4976: 	$scantron_config{'CODEstart'} &&
                   4977: 	$scantron_config{'CODElength'}) {
                   4978: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 4979: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 4980: 	$CODElist=
                   4981: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 4982: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 4983:     }
1.203     albertel 4984:     return (<<STUFF);
                   4985: <p>
1.398     albertel 4986: <span class="LC_warning">Please double check the information
                   4987:                  below before clicking on '$button_text'</span>
1.203     albertel 4988: </p>
                   4989: <table>
1.284     albertel 4990: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 4991: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 4992: $CODElist
1.203     albertel 4993: </table>
                   4994: <br />
                   4995: <p> If this information is correct, please click on '$button_text'.</p>
                   4996: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   4997: 
                   4998: <br />
                   4999: STUFF
                   5000: }
                   5001: 
                   5002: sub scantron_do_warning {
                   5003:     my ($r)=@_;
1.324     albertel 5004:     my ($symb)=&get_symb($r);
1.203     albertel 5005:     if (!$symb) {return '';}
1.324     albertel 5006:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5007:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5008:     if ( $env{'form.selectpage'} eq '' ||
                   5009: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5010: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5011: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5012: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5013: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5014: 	} 
1.257     albertel 5015: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5016: 	    $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 5017: 	} 
1.257     albertel 5018: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5019: 	    $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 5020: 	} 
                   5021:     } else {
1.265     www      5022: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5023: 	$r->print(<<STUFF);
1.203     albertel 5024: $warning
1.265     www      5025: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5026: <input type="hidden" name="command" value="scantron_validate" />
                   5027: STUFF
1.237     albertel 5028:     }
1.352     albertel 5029:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5030:     return '';
                   5031: }
                   5032: 
                   5033: sub scantron_form_start {
                   5034:     my ($max_bubble)=@_;
                   5035:     my $result= <<SCANTRONFORM;
                   5036: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5037:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5038:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5039:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5040:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5041:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5042:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5043:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5044:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5045:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5046: SCANTRONFORM
                   5047:     return $result;
                   5048: }
                   5049: 
1.157     albertel 5050: sub scantron_validate_file {
                   5051:     my ($r) = @_;
1.324     albertel 5052:     my ($symb)=&get_symb($r);
1.157     albertel 5053:     if (!$symb) {return '';}
1.324     albertel 5054:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5055:     
                   5056:     # do the detection of only doing skipped records first befroe we delete
                   5057:     # them  when doing the corrections reset
1.257     albertel 5058:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5059: 	&reset_skipping_status();
                   5060:     }
1.257     albertel 5061:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5062: 	&remember_current_skipped();
1.257     albertel 5063: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5064:     }
                   5065: 
1.257     albertel 5066:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5067: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5068: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5069: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5070: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5071:     }
1.200     albertel 5072: 
1.257     albertel 5073:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5074: 	&scantron_process_corrections($r);
                   5075:     }
1.191     albertel 5076:     $r->print("<p>Gathering neccessary info.</p>");$r->rflush();
1.157     albertel 5077:     #get the student pick code ready
                   5078:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5079:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5080:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5081:     $r->print($result);
                   5082:     
1.334     albertel 5083:     my @validate_phases=( 'sequence',
                   5084: 			  'ID',
1.157     albertel 5085: 			  'CODE',
                   5086: 			  'doublebubble',
                   5087: 			  'missingbubbles');
1.257     albertel 5088:     if (!$env{'form.validatepass'}) {
                   5089: 	$env{'form.validatepass'} = 0;
1.157     albertel 5090:     }
1.257     albertel 5091:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5092: 
                   5093:     my $stop=0;
                   5094:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5095: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5096: 	$r->rflush();
                   5097: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5098: 	{
                   5099: 	    no strict 'refs';
                   5100: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5101: 	}
                   5102:     }
                   5103:     if (!$stop) {
1.203     albertel 5104: 	my $warning=&scantron_warning_screen('Start Grading');
                   5105: 	$r->print(<<STUFF);
                   5106: Validation process complete.<br />
                   5107: $warning
                   5108: <input type="submit" name="submit" value="Start Grading" />
                   5109: <input type="hidden" name="command" value="scantron_process" />
                   5110: STUFF
                   5111: 
1.157     albertel 5112:     } else {
                   5113: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5114: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5115:     }
                   5116:     if ($stop) {
1.334     albertel 5117: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5118: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5119: 	    $r->print(' this error <br />');
                   5120: 
                   5121: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5122: 	} else {
                   5123: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5124: 	    $r->print(' using corrected info <br />');
                   5125: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5126: 	    $r->print(" this scanline saving it for later.");
                   5127: 	}
1.157     albertel 5128:     }
1.352     albertel 5129:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5130:     return '';
                   5131: }
                   5132: 
1.200     albertel 5133: sub scantron_remove_file {
1.192     albertel 5134:     my ($which)=@_;
1.257     albertel 5135:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5136:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5137:     my $file='scantron_';
1.200     albertel 5138:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5139: 	$file.=$which.'_';
1.192     albertel 5140:     } else {
                   5141: 	return 'refused';
                   5142:     }
1.257     albertel 5143:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5144:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5145: }
                   5146: 
                   5147: sub scantron_remove_scan_data {
1.257     albertel 5148:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5149:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5150:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5151:     my @todelete;
1.257     albertel 5152:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5153:     foreach my $key (@keys) {
                   5154: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5155: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5156: 		$key=~/remember_skipping/) {
                   5157: 		next;
                   5158: 	    }
1.192     albertel 5159: 	    push(@todelete,$key);
                   5160: 	}
                   5161:     }
1.200     albertel 5162:     my $result;
1.192     albertel 5163:     if (@todelete) {
1.200     albertel 5164: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5165:     }
                   5166:     return $result;
                   5167: }
                   5168: 
1.157     albertel 5169: sub scantron_getfile {
1.200     albertel 5170:     #FIXME really would prefer a scantron directory
1.257     albertel 5171:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5172:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5173:     my $lines;
                   5174:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5175: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5176:     my %scanlines;
                   5177:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5178:     my $temp=$scanlines{'orig'};
                   5179:     $scanlines{'count'}=$#$temp;
                   5180: 
                   5181:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5182: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5183:     if ($lines eq '-1') {
                   5184: 	$scanlines{'corrected'}=[];
                   5185:     } else {
                   5186: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5187:     }
                   5188:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5189: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5190:     if ($lines eq '-1') {
                   5191: 	$scanlines{'skipped'}=[];
                   5192:     } else {
                   5193: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5194:     }
1.175     albertel 5195:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5196:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5197:     my %scan_data = @tmp;
                   5198:     return (\%scanlines,\%scan_data);
                   5199: }
                   5200: 
                   5201: sub lonnet_putfile {
                   5202:     my ($contents,$filename)=@_;
1.257     albertel 5203:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5204:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5205:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 5206:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 5207: 
                   5208: }
                   5209: 
                   5210: sub scantron_putfile {
                   5211:     my ($scanlines,$scan_data) = @_;
1.200     albertel 5212:     #FIXME really would prefer a scantron directory
1.257     albertel 5213:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5214:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 5215:     if ($scanlines) {
                   5216: 	my $prefix='scantron_';
1.157     albertel 5217: # no need to update orig, shouldn't change
                   5218: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 5219: #		    $env{'form.scantron_selectfile'});
1.200     albertel 5220: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   5221: 			$prefix.'corrected_'.
1.257     albertel 5222: 			$env{'form.scantron_selectfile'});
1.200     albertel 5223: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   5224: 			$prefix.'skipped_'.
1.257     albertel 5225: 			$env{'form.scantron_selectfile'});
1.200     albertel 5226:     }
1.175     albertel 5227:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 5228: }
                   5229: 
                   5230: sub scantron_get_line {
1.200     albertel 5231:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 5232:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   5233:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 5234:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   5235:     return $scanlines->{'orig'}[$i]; 
                   5236: }
                   5237: 
1.200     albertel 5238: sub get_todo_count {
                   5239:     my ($scanlines,$scan_data)=@_;
                   5240:     my $count=0;
                   5241:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5242: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   5243: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5244: 	$count++;
                   5245:     }
                   5246:     return $count;
                   5247: }
                   5248: 
1.157     albertel 5249: sub scantron_put_line {
1.200     albertel 5250:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 5251:     if ($skip) {
                   5252: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 5253: 	&start_skipping($scan_data,$i);
1.157     albertel 5254: 	return;
                   5255:     }
                   5256:     $scanlines->{'corrected'}[$i]=$newline;
                   5257: }
                   5258: 
1.376     albertel 5259: sub scantron_clear_skip {
                   5260:     my ($scanlines,$scan_data,$i)=@_;
                   5261:     if (exists($scanlines->{'skipped'}[$i])) {
                   5262: 	undef($scanlines->{'skipped'}[$i]);
                   5263: 	return 1;
                   5264:     }
                   5265:     return 0;
                   5266: }
                   5267: 
1.334     albertel 5268: sub scantron_filter_not_exam {
                   5269:     my ($curres)=@_;
                   5270:     
                   5271:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   5272: 	# if the user has asked to not have either hidden
                   5273: 	# or 'randomout' controlled resources to be graded
                   5274: 	# don't include them
                   5275: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5276: 	    && $curres->randomout) {
                   5277: 	    return 0;
                   5278: 	}
                   5279: 	return 1;
                   5280:     }
                   5281:     return 0;
                   5282: }
                   5283: 
                   5284: sub scantron_validate_sequence {
                   5285:     my ($r,$currentphase) = @_;
                   5286: 
                   5287:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5288:     my (undef,undef,$sequence)=
                   5289: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   5290: 
                   5291:     my $map=$navmap->getResourceByUrl($sequence);
                   5292: 
                   5293:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   5294:                                     value="ignore" />');
                   5295:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   5296: 	my @resources=
                   5297: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   5298: 	if (@resources) {
1.357     banghart 5299: 	    $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 5300: 	    return (1,$currentphase);
                   5301: 	}
                   5302:     }
                   5303: 
                   5304:     return (0,$currentphase+1);
                   5305: }
                   5306: 
1.157     albertel 5307: sub scantron_validate_ID {
                   5308:     my ($r,$currentphase) = @_;
                   5309:     
                   5310:     #get student info
                   5311:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5312:     my %idmap=&username_to_idmap($classlist);
                   5313: 
                   5314:     #get scantron line setup
1.257     albertel 5315:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5316:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5317: 
                   5318:     my %found=('ids'=>{},'usernames'=>{});
                   5319:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5320: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5321: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5322: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5323: 						 $scan_data);
                   5324: 	my $id=$$scan_record{'scantron.ID'};
                   5325: 	my $found;
                   5326: 	foreach my $checkid (keys(%idmap)) {
                   5327: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   5328: 	}
                   5329: 	if ($found) {
                   5330: 	    my $username=$idmap{$found};
                   5331: 	    if ($found{'ids'}{$found}) {
                   5332: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5333: 					 $line,'duplicateID',$found);
1.194     albertel 5334: 		return(1,$currentphase);
1.157     albertel 5335: 	    } elsif ($found{'usernames'}{$username}) {
                   5336: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5337: 					 $line,'duplicateID',$username);
1.194     albertel 5338: 		return(1,$currentphase);
1.157     albertel 5339: 	    }
1.186     albertel 5340: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 5341: 	    $found{'ids'}{$found}++;
                   5342: 	    $found{'usernames'}{$username}++;
                   5343: 	} else {
                   5344: 	    if ($id =~ /^\s*$/) {
1.158     albertel 5345: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 5346: 		if (defined($username) && $found{'usernames'}{$username}) {
                   5347: 		    &scantron_get_correction($r,$i,$scan_record,
                   5348: 					     \%scantron_config,
                   5349: 					     $line,'duplicateID',$username);
1.194     albertel 5350: 		    return(1,$currentphase);
1.157     albertel 5351: 		} elsif (!defined($username)) {
                   5352: 		    &scantron_get_correction($r,$i,$scan_record,
                   5353: 					     \%scantron_config,
                   5354: 					     $line,'incorrectID');
1.194     albertel 5355: 		    return(1,$currentphase);
1.157     albertel 5356: 		}
                   5357: 		$found{'usernames'}{$username}++;
                   5358: 	    } else {
                   5359: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5360: 					 $line,'incorrectID');
1.194     albertel 5361: 		return(1,$currentphase);
1.157     albertel 5362: 	    }
                   5363: 	}
                   5364:     }
                   5365: 
                   5366:     return (0,$currentphase+1);
                   5367: }
                   5368: 
                   5369: sub scantron_get_correction {
                   5370:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   5371: 
                   5372: #FIXME in the case of a duplicated ID the previous line, probaly need
                   5373: #to show both the current line and the previous one and allow skipping
                   5374: #the previous one or the current one
                   5375: 
1.161     albertel 5376:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 5377:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 5378: 	$r->print(" for PaperID <tt>".
                   5379: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   5380:     } else {
                   5381: 	$r->print(" in scanline $i <pre>".
                   5382: 		  $line."</pre> \n");
                   5383:     }
1.242     albertel 5384:     my $message="<p>The ID on the form is  <tt>".
                   5385: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   5386: 	"The name on the paper is ".
                   5387: 	$$scan_record{'scantron.LastName'}.",".
                   5388: 	$$scan_record{'scantron.FirstName'}."</p>";
                   5389: 
1.157     albertel 5390:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   5391:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   5392:     if ($error =~ /ID$/) {
1.186     albertel 5393: 	if ($error eq 'incorrectID') {
1.157     albertel 5394: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   5395: 	} elsif ($error eq 'duplicateID') {
                   5396: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   5397: 	}
1.242     albertel 5398: 	$r->print($message);
1.157     albertel 5399: 	$r->print("<p>How should I handle this? <br /> \n");
                   5400: 	$r->print("\n<ul><li> ");
                   5401: 	#FIXME it would be nice if this sent back the user ID and
                   5402: 	#could do partial userID matches
                   5403: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   5404: 				       'scantron_username','scantron_domain'));
                   5405: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   5406: 	$r->print("\n@".
1.257     albertel 5407: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 5408: 
                   5409: 	$r->print('</li>');
1.186     albertel 5410:     } elsif ($error =~ /CODE$/) {
                   5411: 	if ($error eq 'incorrectCODE') {
1.187     albertel 5412: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 5413: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 5414: 	    $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 5415: 	}
1.224     albertel 5416: 	$r->print("<p>The CODE on the form is  <tt>'".
                   5417: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 5418: 	$r->print($message);
1.186     albertel 5419: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 5420: 	$r->print("\n<br /> ");
1.194     albertel 5421: 	my $i=0;
1.273     albertel 5422: 	if ($error eq 'incorrectCODE' 
                   5423: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 5424: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 5425: 	    if ($closest > 0) {
                   5426: 		foreach my $testcode (@{$closest}) {
                   5427: 		    my $checked='';
                   5428: 		    if (!$i) { $checked=' checked="on" '; }
                   5429: 		    $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' />");
                   5430: 		    $r->print("\n<br />");
                   5431: 		    $i++;
                   5432: 		}
1.194     albertel 5433: 	    }
                   5434: 	}
1.273     albertel 5435: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
                   5436: 	    my $checked; if (!$i) { $checked=' checked="on" '; }
                   5437: 	    $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>");
                   5438: 	    $r->print("\n<br />");
                   5439: 	}
1.194     albertel 5440: 
1.188     albertel 5441: 	$r->print(<<ENDSCRIPT);
                   5442: <script type="text/javascript">
                   5443: function change_radio(field) {
1.190     albertel 5444:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 5445:     var i;
                   5446:     for (i=0;i<slct.length;i++) {
                   5447:         if (slct[i].value==field) { slct[i].checked=true; }
                   5448:     }
                   5449: }
                   5450: </script>
                   5451: ENDSCRIPT
1.187     albertel 5452: 	my $href="/adm/pickcode?".
1.359     www      5453: 	   "form=".&escape("scantronupload").
                   5454: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   5455: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   5456: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   5457: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 5458: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   5459: 	    $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')\" />");
                   5460: 	    $r->print("\n<br />");
                   5461: 	}
1.272     albertel 5462: 	$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 5463: 	$r->print("\n<br /><br />");
1.157     albertel 5464:     } elsif ($error eq 'doublebubble') {
                   5465: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   5466: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   5467: 		  join(',',@{$arg}).'" />');
1.242     albertel 5468: 	$r->print($message);
1.157     albertel 5469: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   5470: 	foreach my $question (@{$arg}) {
                   5471: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   5472: 	    &scantron_bubble_selector($r,$scan_config,$question,split('',$selected));
                   5473: 	}
                   5474:     } elsif ($error eq 'missingbubble') {
                   5475: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 5476: 	$r->print($message);
1.157     albertel 5477: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   5478: 	$r->print("Some questions have no scanned bubbles\n");
                   5479: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   5480: 		  join(',',@{$arg}).'" />');
                   5481: 	foreach my $question (@{$arg}) {
                   5482: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   5483: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   5484: 	}
                   5485:     } else {
                   5486: 	$r->print("\n<ul>");
                   5487:     }
                   5488:     $r->print("\n</li></ul>");
                   5489: 
                   5490: }
                   5491: 
                   5492: sub scantron_bubble_selector {
                   5493:     my ($r,$scan_config,$quest,@selected)=@_;
                   5494:     my $max=$$scan_config{'Qlength'};
1.274     albertel 5495: 
                   5496:     my $scmode=$$scan_config{'Qon'};
                   5497:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   5498: 
1.157     albertel 5499:     my @alphabet=('A'..'Z');
                   5500:     $r->print("<table border='1'><tr><td rowspan='2'>$quest</td>");
                   5501:     for (my $i=0;$i<$max+1;$i++) {
1.274     albertel 5502: 	$r->print("\n".'<td align="center">');
1.157     albertel 5503: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   5504: 	else { $r->print('&nbsp;'); }
                   5505: 	$r->print('</td>');
                   5506:     }
1.274     albertel 5507:     $r->print('</tr><tr>');
1.157     albertel 5508:     for (my $i=0;$i<$max;$i++) {
1.274     albertel 5509: 	$r->print("\n".
                   5510: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
1.272     albertel 5511: 		  $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
1.157     albertel 5512:     }
1.272     albertel 5513:     $r->print('<td><label><input type="radio" name="scantron_correct_Q_'.
                   5514: 	      $quest.'" value="none" /> No bubble </label></td>');
1.157     albertel 5515:     $r->print('</tr></table>');
                   5516: }
                   5517: 
1.194     albertel 5518: sub num_matches {
                   5519:     my ($orig,$code) = @_;
                   5520:     my @code=split(//,$code);
                   5521:     my @orig=split(//,$orig);
                   5522:     my $same=0;
                   5523:     for (my $i=0;$i<scalar(@code);$i++) {
                   5524: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   5525:     }
                   5526:     return $same;
                   5527: }
                   5528: 
                   5529: sub scantron_get_closely_matching_CODEs {
                   5530:     my ($allcodes,$CODE)=@_;
                   5531:     my @CODEs;
                   5532:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   5533: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   5534:     }
                   5535: 
                   5536:     return ($#CODEs,$CODEs[-1]);
                   5537: }
                   5538: 
                   5539: sub get_codes {
1.280     foxr     5540:     my ($old_name, $cdom, $cnum) = @_;
                   5541:     if (!$old_name) {
                   5542: 	$old_name=$env{'form.scantron_CODElist'};
                   5543:     }
                   5544:     if (!$cdom) {
                   5545: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5546:     }
                   5547:     if (!$cnum) {
                   5548: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   5549:     }
1.278     albertel 5550:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   5551: 				    $cdom,$cnum);
                   5552:     my %allcodes;
                   5553:     if ($result{"type\0$old_name"} eq 'number') {
                   5554: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   5555:     } else {
                   5556: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   5557:     }
1.194     albertel 5558:     return %allcodes;
                   5559: }
                   5560: 
1.157     albertel 5561: sub scantron_validate_CODE {
                   5562:     my ($r,$currentphase) = @_;
1.257     albertel 5563:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 5564:     if ($scantron_config{'CODElocation'} &&
                   5565: 	$scantron_config{'CODEstart'} &&
                   5566: 	$scantron_config{'CODElength'}) {
1.257     albertel 5567: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 5568: 	    &FIXME_blow_up()
                   5569: 	}
                   5570:     } else {
                   5571: 	return (0,$currentphase+1);
                   5572:     }
                   5573:     
                   5574:     my %usedCODEs;
                   5575: 
1.194     albertel 5576:     my %allcodes=&get_codes();
1.186     albertel 5577: 
                   5578:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5579:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5580: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 5581: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5582: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5583: 						 $scan_data);
                   5584: 	my $CODE=$$scan_record{'scantron.CODE'};
                   5585: 	my $error=0;
1.224     albertel 5586: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   5587: 	    &scantron_get_correction($r,$i,$scan_record,
                   5588: 				     \%scantron_config,
                   5589: 				     $line,'incorrectCODE',\%allcodes);
                   5590: 	    return(1,$currentphase);
                   5591: 	}
1.221     albertel 5592: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   5593: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 5594: 	    &scantron_get_correction($r,$i,$scan_record,
                   5595: 				     \%scantron_config,
1.194     albertel 5596: 				     $line,'incorrectCODE',\%allcodes);
                   5597: 	    return(1,$currentphase);
1.186     albertel 5598: 	}
1.214     albertel 5599: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 5600: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 5601: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 5602: 	    &scantron_get_correction($r,$i,$scan_record,
                   5603: 				     \%scantron_config,
1.194     albertel 5604: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   5605: 	    return(1,$currentphase);
1.186     albertel 5606: 	}
1.194     albertel 5607: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 5608:     }
1.157     albertel 5609:     return (0,$currentphase+1);
                   5610: }
                   5611: 
                   5612: sub scantron_validate_doublebubble {
                   5613:     my ($r,$currentphase) = @_;
                   5614:     #get student info
                   5615:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5616:     my %idmap=&username_to_idmap($classlist);
                   5617: 
                   5618:     #get scantron line setup
1.257     albertel 5619:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5620:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5621:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5622: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5623: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5624: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5625: 						 $scan_data);
                   5626: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   5627: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   5628: 				 'doublebubble',
                   5629: 				 $$scan_record{'scantron.doubleerror'});
                   5630:     	return (1,$currentphase);
                   5631:     }
                   5632:     return (0,$currentphase+1);
                   5633: }
                   5634: 
1.330     albertel 5635: sub scantron_get_maxbubble {    
1.257     albertel 5636:     if (defined($env{'form.scantron_maxbubble'}) &&
                   5637: 	$env{'form.scantron_maxbubble'}) {
                   5638: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 5639:     }
1.330     albertel 5640: 
1.191     albertel 5641:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5642:     my (undef,undef,$sequence)=
1.257     albertel 5643: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 5644: 
1.191     albertel 5645:     my $map=$navmap->getResourceByUrl($sequence);
                   5646:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 5647: 
                   5648:     &Apache::lonxml::clear_problem_counter();
                   5649: 
1.191     albertel 5650:     foreach my $resource (@resources) {
1.330     albertel 5651: 	my $result=&Apache::lonnet::ssi($resource->src(),
                   5652: 					('symb' => $resource->symb()));
1.191     albertel 5653:     }
                   5654:     &Apache::lonnet::delenv('scantron\.');
1.330     albertel 5655:     $env{'form.scantron_maxbubble'} =
                   5656: 	&Apache::lonxml::get_problem_counter()-1;
                   5657: 
1.257     albertel 5658:     return $env{'form.scantron_maxbubble'};
1.191     albertel 5659: }
                   5660: 
1.157     albertel 5661: sub scantron_validate_missingbubbles {
                   5662:     my ($r,$currentphase) = @_;
                   5663:     #get student info
                   5664:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5665:     my %idmap=&username_to_idmap($classlist);
                   5666: 
                   5667:     #get scantron line setup
1.257     albertel 5668:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5669:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 5670:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 5671:     if (!$max_bubble) { $max_bubble=2**31; }
                   5672:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5673: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5674: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5675: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5676: 						 $scan_data);
                   5677: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   5678: 	my @to_correct;
                   5679: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   5680: 	    if ($missing > $max_bubble) { next; }
                   5681: 	    push(@to_correct,$missing);
                   5682: 	}
                   5683: 	if (@to_correct) {
                   5684: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5685: 				     $line,'missingbubble',\@to_correct);
                   5686: 	    return (1,$currentphase);
                   5687: 	}
                   5688: 
                   5689:     }
                   5690:     return (0,$currentphase+1);
                   5691: }
                   5692: 
1.82      albertel 5693: sub scantron_process_students {
1.75      albertel 5694:     my ($r) = @_;
1.257     albertel 5695:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 5696:     my ($symb)=&get_symb($r);
1.81      albertel 5697:     if (!$symb) {return '';}
1.324     albertel 5698:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 5699: 
1.257     albertel 5700:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5701:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 5702:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5703:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 5704:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 5705:     my $map=$navmap->getResourceByUrl($sequence);
                   5706:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 5707: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 5708:     my $result= <<SCANTRONFORM;
1.81      albertel 5709: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   5710:   <input type="hidden" name="command" value="scantron_configphase" />
                   5711:   $default_form_data
                   5712: SCANTRONFORM
1.82      albertel 5713:     $r->print($result);
                   5714: 
                   5715:     my @delayqueue;
1.140     albertel 5716:     my %completedstudents;
                   5717:     
1.200     albertel 5718:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 5719:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 5720:  				    'Scantron Progress',$count,
1.195     albertel 5721: 				    'inline',undef,'scantronupload');
1.140     albertel 5722:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   5723: 					  'Processing first student');
                   5724:     my $start=&Time::HiRes::time();
1.158     albertel 5725:     my $i=-1;
1.200     albertel 5726:     my ($uname,$udom,$started);
1.157     albertel 5727:     while ($i<$scanlines->{'count'}) {
                   5728:  	($uname,$udom)=('','');
                   5729:  	$i++;
1.200     albertel 5730:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5731:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 5732: 	if ($started) {
                   5733: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   5734: 						     'last student');
                   5735: 	}
                   5736: 	$started=1;
1.157     albertel 5737:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5738:  						 $scan_data);
                   5739:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   5740:  					      \%idmap,$i)) {
                   5741:   	    &scantron_add_delay(\@delayqueue,$line,
                   5742:  				'Unable to find a student that matches',1);
                   5743:  	    next;
                   5744:   	}
                   5745:  	if (exists $completedstudents{$uname}) {
                   5746:  	    &scantron_add_delay(\@delayqueue,$line,
                   5747:  				'Student '.$uname.' has multiple sheets',2);
                   5748:  	    next;
                   5749:  	}
                   5750:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 5751: 
                   5752: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 5753:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 5754: 
                   5755: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   5756: 	    &scantron_putfile($scanlines,$scan_data);
                   5757: 	}
1.161     albertel 5758: 	
                   5759: 	my $i=0;
1.83      albertel 5760: 	foreach my $resource (@resources) {
1.85      albertel 5761: 	    $i++;
1.193     albertel 5762: 	    my %form=('submitted'     =>'scantron',
                   5763: 		      'grade_target'  =>'grade',
                   5764: 		      'grade_username'=>$uname,
                   5765: 		      'grade_domain'  =>$udom,
1.257     albertel 5766: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 5767: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 5768: 	    if (exists($scan_record->{'scantron.CODE'})
                   5769: 		&& 
                   5770: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 5771: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 5772: 	    } else {
                   5773: 		$form{'CODE'}='';
1.193     albertel 5774: 	    }
                   5775: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 5776: 	    if ($result ne '') {
                   5777: 		&Apache::lonnet::logthis("scantron grading error -> $result");
1.257     albertel 5778: 		&Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
1.227     albertel 5779: 	    }
1.213     albertel 5780: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 5781: 	}
1.140     albertel 5782: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 5783: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 5784:     } continue {
1.330     albertel 5785: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 5786: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 5787:     }
1.140     albertel 5788:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 5789: #    my $lasttime = &Time::HiRes::time()-$start;
                   5790: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 5791: 
1.200     albertel 5792:     $r->print("</form>");
1.324     albertel 5793:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 5794:     return '';
1.75      albertel 5795: }
1.157     albertel 5796: 
                   5797: sub scantron_upload_scantron_data {
                   5798:     my ($r)=@_;
1.257     albertel 5799:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 5800:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 5801: 							  'domainid',
                   5802: 							  'coursename');
1.257     albertel 5803:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 5804: 						   'domainid');
1.324     albertel 5805:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 5806:     $r->print(<<UPLOAD);
                   5807: <script type="text/javascript" language="javascript">
                   5808:     function checkUpload(formname) {
                   5809: 	if (formname.upfile.value == "") {
                   5810: 	    alert("Please use the browse button to select a file from your local directory.");
                   5811: 	    return false;
                   5812: 	}
                   5813: 	formname.submit();
                   5814:     }
                   5815: </script>
                   5816: 
                   5817: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 5818: $default_form_data
1.181     albertel 5819: <table>
                   5820: <tr><td>$select_link </td></tr>
                   5821: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   5822: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   5823: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   5824: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   5825: </table>
1.157     albertel 5826: <input name='command' value='scantronupload_save' type='hidden' />
                   5827: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   5828: </form>
                   5829: UPLOAD
                   5830:     return '';
                   5831: }
                   5832: 
                   5833: sub scantron_upload_scantron_data_save {
                   5834:     my($r)=@_;
1.324     albertel 5835:     my ($symb)=&get_symb($r,1);
1.182     albertel 5836:     my $doanotherupload=
                   5837: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   5838: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   5839: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   5840: 	'</form>'."\n";
1.257     albertel 5841:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 5842: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 5843: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 5844: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 5845: 	if ($symb) {
1.324     albertel 5846: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 5847: 	} else {
                   5848: 	    $r->print($doanotherupload);
                   5849: 	}
1.162     albertel 5850: 	return '';
                   5851:     }
1.257     albertel 5852:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       5853:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 5854:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 5855:     #FIXME
                   5856:     #copied from lonnet::userfileupload()
                   5857:     #make that function able to target a specified course
                   5858:     # Replace Windows backslashes by forward slashes
                   5859:     $fname=~s/\\/\//g;
                   5860:     # Get rid of everything but the actual filename
                   5861:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   5862:     # Replace spaces by underscores
                   5863:     $fname=~s/\s+/\_/g;
                   5864:     # Replace all other weird characters by nothing
                   5865:     $fname=~s/[^\w\.\-]//g;
                   5866:     # See if there is anything left
                   5867:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       5868:     my $uploadedfile=$fname;
1.157     albertel 5869:     $fname='scantron_orig_'.$fname;
1.257     albertel 5870:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 5871: 	$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 5872:     } else {
1.275     albertel 5873: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 5874: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 5875: 	    $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 5876: 	} else {
1.398     albertel 5877: 	    $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 5878: 	}
                   5879:     }
1.174     albertel 5880:     if ($symb) {
1.209     ng       5881: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 5882:     } else {
1.182     albertel 5883: 	$r->print($doanotherupload);
1.174     albertel 5884:     }
1.157     albertel 5885:     return '';
                   5886: }
                   5887: 
1.202     albertel 5888: sub valid_file {
                   5889:     my ($requested_file)=@_;
                   5890:     foreach my $filename (sort(&scantron_filenames())) {
                   5891: 	if ($requested_file eq $filename) { return 1; }
                   5892:     }
                   5893:     return 0;
                   5894: }
                   5895: 
                   5896: sub scantron_download_scantron_data {
                   5897:     my ($r)=@_;
1.324     albertel 5898:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5899:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5900:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5901:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 5902:     if (! &valid_file($file)) {
                   5903: 	$r->print(<<ERROR);
                   5904: 	<p>
                   5905: 	    The requested file name was invalid.
                   5906:         </p>
                   5907: ERROR
1.324     albertel 5908: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 5909: 	return;
                   5910:     }
                   5911:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   5912:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   5913:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   5914:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   5915:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   5916:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   5917:     $r->print(<<DOWNLOAD);
                   5918:     <p>
                   5919: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   5920:     </p>
                   5921:     <p>
                   5922: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   5923:     </p>
                   5924:     <p>
                   5925: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   5926:     </p>
                   5927: DOWNLOAD
1.324     albertel 5928:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 5929:     return '';
                   5930: }
1.157     albertel 5931: 
1.75      albertel 5932: #-------- end of section for handling grading scantron forms -------
                   5933: #
                   5934: #-------------------------------------------------------------------
                   5935: 
1.72      ng       5936: #-------------------------- Menu interface -------------------------
                   5937: #
                   5938: #--- Show a Grading Menu button - Calls the next routine ---
                   5939: sub show_grading_menu_form {
1.324     albertel 5940:     my ($symb)=@_;
1.125     ng       5941:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.72      ng       5942: 	'<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
1.257     albertel 5943: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       5944: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   5945: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   5946: 	'</form>'."\n";
                   5947:     return $result;
                   5948: }
                   5949: 
1.77      ng       5950: # -- Retrieve choices for grading form
                   5951: sub savedState {
                   5952:     my %savedState = ();
1.257     albertel 5953:     if ($env{'form.saveState'}) {
                   5954: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       5955: 	    my ($key,$value) = split(/=/,$_,2);
                   5956: 	    $savedState{$key} = $value;
                   5957: 	}
                   5958:     }
                   5959:     return \%savedState;
                   5960: }
1.76      ng       5961: 
1.72      ng       5962: #--- Displays the main menu page -------
                   5963: sub gradingmenu {
                   5964:     my ($request) = @_;
1.324     albertel 5965:     my ($symb)=&get_symb($request);
1.72      ng       5966:     if (!$symb) {return '';}
1.76      ng       5967:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       5968: 
                   5969:     $request->print(<<GRADINGMENUJS);
                   5970: <script type="text/javascript" language="javascript">
1.116     ng       5971:     function checkChoice(formname,val,cmdx) {
                   5972: 	if (val <= 2) {
                   5973: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       5974: 	    var cmdsave = cmd;
1.116     ng       5975: 	} else {
                   5976: 	    cmd = cmdx;
1.118     ng       5977: 	    cmdsave = 'submission';
1.116     ng       5978: 	}
                   5979: 	formname.command.value = cmd;
1.118     ng       5980: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 5981: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       5982: 	if (val < 5) formname.submit();
                   5983: 	if (val == 5) {
1.72      ng       5984: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   5985: 	    formname.submit();
                   5986: 	}
1.238     albertel 5987: 	if (val < 7) formname.submit();
1.72      ng       5988:     }
                   5989: 
                   5990:     function checkReceiptNo(formname,nospace) {
                   5991: 	var receiptNo = formname.receipt.value;
                   5992: 	var checkOpt = false;
                   5993: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   5994: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   5995: 	if (checkOpt) {
                   5996: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   5997: 	    formname.receipt.value = "";
                   5998: 	    formname.receipt.focus();
                   5999: 	    return false;
                   6000: 	}
                   6001: 	return true;
                   6002:     }
                   6003: </script>
                   6004: GRADINGMENUJS
1.118     ng       6005:     &commonJSfunctions($request);
1.398     albertel 6006:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
1.324     albertel 6007:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       6008:     $result.=$table;
1.76      ng       6009:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       6010:     my $savedState = &savedState();
1.118     ng       6011:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       6012:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       6013:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       6014:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       6015: 
                   6016:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   6017: 	'<input type="hidden" name="symb"        value="'.$symb.'" />'."\n".
                   6018: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   6019: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       6020: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       6021: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       6022: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       6023: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   6024: 
1.326     albertel 6025:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   6026: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
1.72      ng       6027: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       6028: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   6029: 
1.326     albertel 6030:     $result.='<table width="100%" border="0">';
1.116     ng       6031:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.167     sakharuk 6032: 	'&nbsp;'.&mt('Select Section').': <select name="section">'."\n";
1.116     ng       6033:     if (ref($sections)) {
1.155     albertel 6034: 	foreach (sort (@$sections)) {
                   6035: 	    $result.='<option value="'.$_.'" '.
                   6036: 		($saveSec eq $_ ? 'selected="on"':'').'>'.$_.'</option>'."\n";
                   6037: 	}
1.116     ng       6038:     }
1.238     albertel 6039:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="on"' : ''). '>all</option></select> &nbsp; ';
1.116     ng       6040: 
1.167     sakharuk 6041:     $result.=&mt('Student Status').':</b>'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
1.72      ng       6042: 
1.116     ng       6043:     $result.='</td></tr>';
                   6044: 
1.288     albertel 6045:     $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
1.118     ng       6046: 	'<input type="radio" name="radioChoice" value="submission" '.
1.326     albertel 6047: 	($saveCmd eq 'submission' ? 'checked' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 6048: 	'</label> <select name="submitonly">'.
1.145     albertel 6049: 	'<option value="yes" '.
1.326     albertel 6050: 	($saveSub eq 'yes' ? 'selected="on"' : '').' />'.&mt('with submissions').'</option>'.
1.301     albertel 6051: 	'<option value="queued" '.
1.326     albertel 6052: 	($saveSub eq 'queued' ? 'selected="on"' : '').' />'.&mt('in grading queue').'</option>'.
1.145     albertel 6053: 	'<option value="graded" '.
1.326     albertel 6054: 	($saveSub eq 'graded' ? 'selected="on"' : '').' />'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 6055: 	'<option value="incorrect" '.
1.326     albertel 6056: 	($saveSub eq 'incorrect' ? 'selected="on"' : '').' />'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 6057: 	'<option value="all" '.
1.326     albertel 6058: 	($saveSub eq 'all' ? 'selected="on"' : '').' />'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       6059: 
1.116     ng       6060:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.288     albertel 6061: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.326     albertel 6062: 	($saveCmd eq 'viewgrades' ? 'checked' : '').' /> '.
1.288     albertel 6063: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       6064: 
1.118     ng       6065:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
1.288     albertel 6066: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.326     albertel 6067: 	($saveCmd eq 'pickStudentPage' ? 'checked' : '').' /> '.
1.288     albertel 6068: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       6069: 
1.116     ng       6070:     $result.='<tr bgcolor="#ffffe6"><td><br />'.
1.126     ng       6071: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       6072: 	'</td></tr></table>'."\n";
                   6073: 
                   6074:     $result.='</td><td valign="top">';
                   6075: 
1.326     albertel 6076:     $result.='<table width="100%" border="0">';
1.116     ng       6077:     $result.='<tr bgcolor="#ffffe6"><td>'.
1.184     www      6078: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   6079: 	' '.&mt('scores from file').' </td></tr>'."\n";
1.72      ng       6080: 
1.400   ! www      6081: #    $result.='<tr bgcolor="#ffffe6"><td>'.
        !          6082: #        '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
        !          6083: #        ' '.&mt('clicker file').' </td></tr>'."\n";
        !          6084: 
        !          6085: 
1.75      albertel 6086:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.116     ng       6087: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
1.184     www      6088: 	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
1.75      albertel 6089: 
1.257     albertel 6090:     if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
1.72      ng       6091: 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.184     www      6092: 	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   6093: 	    ' '.&mt('receipt').': '.
1.257     albertel 6094: 	    &Apache::lonnet::recprefix($env{'request.course.id'}).
1.326     albertel 6095: 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
1.72      ng       6096: 	    '</td></tr>'."\n";
                   6097:     } 
1.238     albertel 6098:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   6099: 	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   6100: 	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
1.279     albertel 6101:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   6102: 	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   6103: 	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
1.44      ng       6104: 
1.116     ng       6105:     $result.='</form></td></tr></table>'."\n".
1.72      ng       6106: 	'</td></tr></table>'."\n".
                   6107: 	'</td></tr></table>'."\n";
1.44      ng       6108:     return $result;
1.2       albertel 6109: }
                   6110: 
1.285     albertel 6111: sub reset_perm {
                   6112:     undef(%perm);
                   6113: }
                   6114: 
                   6115: sub init_perm {
                   6116:     &reset_perm();
1.300     albertel 6117:     foreach my $test_perm ('vgr','mgr','opa') {
                   6118: 
                   6119: 	my $scope = $env{'request.course.id'};
                   6120: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   6121: 
                   6122: 	    $scope .= '/'.$env{'request.course.sec'};
                   6123: 	    if ( $perm{$test_perm}=
                   6124: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   6125: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   6126: 	    } else {
                   6127: 		delete($perm{$test_perm});
                   6128: 	    }
1.285     albertel 6129: 	}
                   6130:     }
                   6131: }
                   6132: 
1.400   ! www      6133: sub gather_clicker_ids {
        !          6134:     my %clickerids=();
        !          6135: 
        !          6136:     my $classlist = &Apache::loncoursedata::get_classlist();
        !          6137: 
        !          6138:     # Set up a couple variables.
        !          6139:     my $usernameidx = &Apache::loncoursedata::CL_SNAME();
        !          6140:     my $domainidx   = &Apache::loncoursedata::CL_SDOM();
        !          6141: 
        !          6142:     foreach my $student (keys %$classlist) {
        !          6143: 
        !          6144:         my $username = $classlist->{$student}->[$usernameidx];
        !          6145:         my $domain   = $classlist->{$student}->[$domainidx];
        !          6146:         my $clickers =
        !          6147: 	   (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
        !          6148:         foreach my $id (split(/\,/,$clickers)) {
        !          6149:             if (exists($clickerids{$id})) {
        !          6150:                $clickerids{$id}.=','.$username.':'.$domain;
        !          6151:             } else {
        !          6152:                $clickerids{$id}=$username.':'.$domain;
        !          6153:             }
        !          6154:         }
        !          6155:     }
        !          6156:     return %clickerids;
        !          6157: }
        !          6158: 
        !          6159: sub process_clicker {
        !          6160:     my ($r)=@_;
        !          6161:     my ($symb)=&get_symb($r);
        !          6162:     if (!$symb) {return '';}
        !          6163:     my $result=&checkforfile_js();
        !          6164:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
        !          6165:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
        !          6166:     $result.=$table;
        !          6167:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
        !          6168:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
        !          6169:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
        !          6170:         '.</b></td></tr>'."\n";
        !          6171:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
        !          6172:     my $upload=&mt("Upload File");
        !          6173:     my $type=&mt("Type");
        !          6174:     my $selectform=&Apache::loncommon::select_form('iclicker','upfiletype',
        !          6175:                                   ('iclicker' => 'iClicker'));
        !          6176: 
        !          6177:     $result.=<<ENDUPFORM;
        !          6178: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
        !          6179: <input type="hidden" name="symb" value="$symb" />
        !          6180: <input type="hidden" name="command" value="processclickerfile" />
        !          6181: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
        !          6182: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
        !          6183: <input type="file" name="upfile" size="50" />
        !          6184: <br /><label>$type: $selectform</label>
        !          6185: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
        !          6186: </form>
        !          6187: ENDUPFORM
        !          6188:     $result.='</td></tr></table>'."\n".
        !          6189:              '</td></tr></table><br /><br />'."\n";
        !          6190:     $result.=&show_grading_menu_form($symb);
        !          6191:     return $result;
        !          6192: }
        !          6193: 
        !          6194: sub process_clicker_file {
        !          6195:     my ($r)=@_;
        !          6196:     my ($symb)=&get_symb($r);
        !          6197:     if (!$symb) {return '';}
        !          6198:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
        !          6199:     $result.=&show_grading_menu_form($symb);
        !          6200:     my %clickerids=&gather_clicker_ids();
        !          6201:     foreach my $key (keys %clickerids) {
        !          6202:        $result.='<br />'.$key.' - '.$clickerids{$key};
        !          6203:     }
        !          6204:     return $result;
        !          6205: }
        !          6206: 
1.1       albertel 6207: sub handler {
1.41      ng       6208:     my $request=$_[0];
1.102     albertel 6209: 
1.285     albertel 6210:     &reset_perm();
1.257     albertel 6211:     if ($env{'browser.mathml'}) {
1.141     www      6212: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       6213:     } else {
1.141     www      6214: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       6215:     }
                   6216:     $request->send_http_header;
1.44      ng       6217:     return '' if $request->header_only;
1.41      ng       6218:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 6219:     my $symb=&get_symb($request,1);
1.160     albertel 6220:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   6221:     my $command=$commands[0];
                   6222:     if ($#commands > 0) {
                   6223: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   6224:     }
1.353     albertel 6225:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 6226:     if ($symb eq '' && $command eq '') {
1.257     albertel 6227: 	if ($env{'user.adv'}) {
                   6228: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   6229: 		($env{'form.codethree'})) {
                   6230: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   6231: 		    $env{'form.codethree'};
1.41      ng       6232: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   6233: 		    &Apache::lonnet::checkin($token);
                   6234: 		if ($tsymb) {
1.137     albertel 6235: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       6236: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 6237: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   6238: 					  ('grade_username' => $tuname,
                   6239: 					   'grade_domain' => $tudom,
                   6240: 					   'grade_courseid' => $tcrsid,
                   6241: 					   'grade_symb' => $tsymb)));
1.41      ng       6242: 		    } else {
1.45      ng       6243: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 6244: 		    }
1.41      ng       6245: 		} else {
1.45      ng       6246: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       6247: 		}
1.14      www      6248: 	    } else {
1.41      ng       6249: 		$request->print(&Apache::lonxml::tokeninputfield());
                   6250: 	    }
                   6251: 	}
                   6252:     } else {
1.285     albertel 6253: 	&init_perm();
1.104     albertel 6254: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 6255: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 6256: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       6257: 	    &pickStudentPage($request);
1.103     albertel 6258: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       6259: 	    &displayPage($request);
1.104     albertel 6260: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       6261: 	    &updateGradeByPage($request);
1.104     albertel 6262: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       6263: 	    &processGroup($request);
1.104     albertel 6264: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.41      ng       6265: 	    $request->print(&gradingmenu($request));
1.104     albertel 6266: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       6267: 	    $request->print(&viewgrades($request));
1.104     albertel 6268: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       6269: 	    $request->print(&processHandGrade($request));
1.106     albertel 6270: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       6271: 	    $request->print(&editgrades($request));
1.106     albertel 6272: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       6273: 	    $request->print(&verifyreceipt($request));
1.400   ! www      6274:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
        !          6275:             $request->print(&process_clicker($request));
        !          6276:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
        !          6277:             $request->print(&process_clicker_file($request));
1.106     albertel 6278: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       6279: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 6280: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       6281: 	    $request->print(&csvupload($request));
1.106     albertel 6282: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       6283: 	    $request->print(&csvuploadmap($request));
1.246     albertel 6284: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 6285: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 6286: 		$request->print(&csvuploadoptions($request));
1.41      ng       6287: 	    } else {
1.257     albertel 6288: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   6289: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       6290: 		} else {
1.257     albertel 6291: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       6292: 		}
                   6293: 		$request->print(&csvuploadmap($request));
                   6294: 	    }
1.246     albertel 6295: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   6296: 	    $request->print(&csvuploadassign($request));
1.106     albertel 6297: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 6298: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 6299:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   6300:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 6301: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   6302: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 6303: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 6304: 	    $request->print(&scantron_process_students($request));
1.157     albertel 6305:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 6306:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   6307: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 6308:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 6309:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 6310:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   6311: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 6312:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 6313:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 6314: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 6315:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 6316: 	} elsif ($command) {
1.157     albertel 6317: 	    $request->print("Access Denied ($command)");
1.26      albertel 6318: 	}
1.2       albertel 6319:     }
1.353     albertel 6320:     $request->print(&Apache::loncommon::end_page());
1.44      ng       6321:     return '';
                   6322: }
                   6323: 
1.1       albertel 6324: 1;
                   6325: 
1.13      albertel 6326: __END__;

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