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

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

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