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

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

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