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

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

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