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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.275   ! albertel    4: # $Id: grades.pm,v 1.274 2005/06/05 06:12:16 albertel Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: package Apache::grades;
                     30: use strict;
                     31: use Apache::style;
                     32: use Apache::lonxml;
                     33: use Apache::lonnet;
1.3       albertel   34: use Apache::loncommon;
1.112     ng         35: use Apache::lonhtmlcommon;
1.68      ng         36: use Apache::lonnavmaps;
1.1       albertel   37: use Apache::lonhomework;
1.55      matthew    38: use Apache::loncoursedata;
1.38      ng         39: use Apache::lonmsg qw(:user_normal_msg);
1.1       albertel   40: use Apache::Constants qw(:common);
1.167     sakharuk   41: use Apache::lonlocal;
1.170     albertel   42: use String::Similarity;
1.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.271     albertel 2276:     my @keys;
                   2277:     foreach my $part (@{$partids}) {
                   2278: 	push(@keys,"$symb\0$part\0resettime");
                   2279:     }
                   2280:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2281: 				     $cdom,$cname);
                   2282:     foreach my $part (@{$partids}) {
                   2283: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2284:     }
1.270     albertel 2285:     return %last_resets;
1.269     raeburn  2286: }
                   2287: 
1.251     banghart 2288: # ----------- Handles creating versions for portfolio files as answers
                   2289: sub version_portfiles {
1.263     banghart 2290:     my ($record, $parts_graded, $courseid, $symb, $domain, $stuname, $v_flag) = @_;
                   2291:     my $version_parts = join('|',@$v_flag);
1.255     banghart 2292:     my $parts = join('|', @$parts_graded);
1.252     banghart 2293:     my $portfolio_root = &Apache::loncommon::propath($domain,
                   2294: 						 $stuname).
                   2295: 						'/userfiles/portfolio';
1.255     banghart 2296:     foreach my $key(keys %$record) {
1.259     banghart 2297:         my $new_portfiles;
1.263     banghart 2298:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.259     banghart 2299:             my @v_portfiles;
1.255     banghart 2300:             my @portfiles = split(/,/,$$record{$key});
1.264     banghart 2301:             # &Apache::lonnet::logthis("should be unmarking and remarking");
1.252     banghart 2302:             foreach my $file (@portfiles) {
1.264     banghart 2303:                 &Apache::lonnet::unmark_as_readonly($domain,$stuname,[$symb,$env{'request.course.id'}],$file);
1.255     banghart 2304:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*$)/);
1.252     banghart 2305:                 my $version = 0;
1.255     banghart 2306:                 my @answer_file_parts = split(/\./, $answer_file);
1.252     banghart 2307:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stuname,$portfolio_root);
                   2308:                 my @file_names;
                   2309:                 my @file_name_parts;
1.253     banghart 2310:                 foreach my $row (@dir_list) {
1.255     banghart 2311:                     @file_names = split(/\&/,$row,2);
                   2312:                     @file_name_parts = split(/\./, $file_names[0]);
1.252     banghart 2313:                     # ($file_name_parts[scalar @file_name_parts] eq $answer_file_parts[scalar @answer_file_parts])
                   2314:                     if (($file_name_parts[0] eq $answer_file_parts[0]) && 
1.253     banghart 2315:                         ($file_name_parts[-1] eq $answer_file_parts[-1])) {
1.252     banghart 2316:                         # gets here if filename and extension match, regardless of version
                   2317:                         if (scalar @file_name_parts == 3) { # a versioned file is found
                   2318:                             # so save it for later
                   2319:                             if ($file_name_parts[1] > $version) {$version = $file_name_parts[1]};
                   2320:                         }
                   2321:                     }
                   2322:                 }
1.255     banghart 2323:                 $version++;
1.259     banghart 2324:                 $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stuname/portfolio$directory$answer_file");
                   2325:                 if($env{'form.copy'} eq '-1') {
                   2326:                     &Apache::lonnet::logthis('problem getting file '.$directory.$answer_file);
                   2327:                 } else {
1.275   ! albertel 2328:                    my $copy_result = &Apache::lonnet::finishuserfileupload($stuname,$domain,'copy',
1.256     banghart 2329:                                     '/portfolio'.$directory.$answer_file_parts[0].'.'.$version.'.'.$answer_file_parts[-1]);
1.259     banghart 2330:                     push(@v_portfiles, $answer_file_parts[0].'.'.$version.'.'.$answer_file_parts[-1]);
1.264     banghart 2331:                     &Apache::lonnet::mark_as_readonly($domain,$stuname,
                   2332:                                 ['/portfolio'.$directory.$answer_file_parts[0].'.'.$version.'.'.$answer_file_parts[-1]],
                   2333:                                 [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2334:                 }
1.252     banghart 2335:             }
1.261     albertel 2336:             $$record{$key} = join(',',@v_portfiles);
1.251     banghart 2337:         }
                   2338:     } 
1.259     banghart 2339:     return 'ok';   
1.251     banghart 2340:     
                   2341: }
                   2342: 
1.44      ng       2343: #--------------------------------------------------------------------------------------
                   2344: #
                   2345: #-------------------------- Next few routines handles grading by section or whole class
                   2346: #
                   2347: #--- Javascript to handle grading by section or whole class
1.42      ng       2348: sub viewgrades_js {
                   2349:     my ($request) = shift;
                   2350: 
1.41      ng       2351:     $request->print(<<VIEWJAVASCRIPT);
                   2352: <script type="text/javascript" language="javascript">
1.45      ng       2353:    function writePoint(partid,weight,point) {
1.125     ng       2354: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2355: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2356: 	if (point == "textval") {
1.125     ng       2357: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2358: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2359: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2360: 		var resetbox = false;
                   2361: 		for (var i=0; i<radioButton.length; i++) {
                   2362: 		    if (radioButton[i].checked) {
                   2363: 			textbox.value = i;
                   2364: 			resetbox = true;
                   2365: 		    }
                   2366: 		}
                   2367: 		if (!resetbox) {
                   2368: 		    textbox.value = "";
                   2369: 		}
                   2370: 		return;
                   2371: 	    }
1.109     matthew  2372: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2373: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2374: 				   ") greater than the weight for the part. Accept?");
                   2375: 		if (resp == false) {
                   2376: 		    textbox.value = "";
                   2377: 		    return;
                   2378: 		}
                   2379: 	    }
1.42      ng       2380: 	    for (var i=0; i<radioButton.length; i++) {
                   2381: 		radioButton[i].checked=false;
1.109     matthew  2382: 		if (parseFloat(point) == i) {
1.42      ng       2383: 		    radioButton[i].checked=true;
                   2384: 		}
                   2385: 	    }
1.41      ng       2386: 
1.42      ng       2387: 	} else {
1.125     ng       2388: 	    textbox.value = parseFloat(point);
1.42      ng       2389: 	}
1.41      ng       2390: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2391: 	    var user = document.classgrade["ctr"+i].value;
                   2392: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2393: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2394: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2395: 	    if (saveval != "correct") {
                   2396: 		scorename.value = point;
1.43      ng       2397: 		if (selname[0].selected != true) {
                   2398: 		    selname[0].selected = true;
                   2399: 		}
1.42      ng       2400: 	    }
                   2401: 	}
1.125     ng       2402: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2403:     }
                   2404: 
                   2405:     function writeRadText(partid,weight) {
1.125     ng       2406: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2407: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2408:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2409: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2410: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2411: 	    for (var i=0; i<radioButton.length; i++) {
                   2412: 		radioButton[i].checked=false;
                   2413: 
                   2414: 	    }
                   2415: 	    textbox.value = "";
                   2416: 
                   2417: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2418: 		var user = document.classgrade["ctr"+i].value;
                   2419: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2420: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2421: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2422: 		if ((saveval != "correct") || override) {
1.42      ng       2423: 		    scorename.value = "";
1.125     ng       2424: 		    if (selval[1].selected) {
                   2425: 			selname[1].selected = true;
                   2426: 		    } else {
                   2427: 			selname[2].selected = true;
                   2428: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   2429: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   2430: 		    }
1.42      ng       2431: 		}
                   2432: 	    }
1.43      ng       2433: 	} else {
                   2434: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2435: 		var user = document.classgrade["ctr"+i].value;
                   2436: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2437: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2438: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2439: 		if ((saveval != "correct") || override) {
1.125     ng       2440: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       2441: 		    selname[0].selected = true;
                   2442: 		}
                   2443: 	    }
                   2444: 	}	    
1.42      ng       2445:     }
                   2446: 
                   2447:     function changeSelect(partid,user) {
1.125     ng       2448: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2449: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       2450: 	var point  = textbox.value;
1.125     ng       2451: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       2452: 
1.109     matthew  2453: 	if (isNaN(point) || parseFloat(point) < 0) {
                   2454: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       2455: 	    textbox.value = "";
                   2456: 	    return;
                   2457: 	}
1.109     matthew  2458: 	if (parseFloat(point) > parseFloat(weight)) {
                   2459: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2460: 			       ") greater than the weight of the part. Accept?");
                   2461: 	    if (resp == false) {
                   2462: 		textbox.value = "";
                   2463: 		return;
                   2464: 	    }
                   2465: 	}
1.42      ng       2466: 	selval[0].selected = true;
                   2467:     }
                   2468: 
                   2469:     function changeOneScore(partid,user) {
1.125     ng       2470: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2471: 	if (selval[1].selected || selval[2].selected) {
                   2472: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   2473: 	    if (selval[2].selected) {
                   2474: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   2475: 	    }
1.269     raeburn  2476:         }
1.42      ng       2477:     }
                   2478: 
                   2479:     function resetEntry(numpart) {
                   2480: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       2481: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   2482: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   2483: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   2484: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       2485: 	    for (var i=0; i<radioButton.length; i++) {
                   2486: 		radioButton[i].checked=false;
                   2487: 
                   2488: 	    }
                   2489: 	    textbox.value = "";
                   2490: 	    selval[0].selected = true;
                   2491: 
                   2492: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2493: 		var user = document.classgrade["ctr"+i].value;
                   2494: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2495: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   2496: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   2497: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   2498: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2499: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2500: 		if (saveselval == "excused") {
1.43      ng       2501: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       2502: 		} else {
1.43      ng       2503: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       2504: 		}
                   2505: 	    }
1.41      ng       2506: 	}
1.42      ng       2507:     }
                   2508: 
1.41      ng       2509: </script>
                   2510: VIEWJAVASCRIPT
1.42      ng       2511: }
                   2512: 
1.44      ng       2513: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       2514: sub viewgrades {
                   2515:     my ($request) = shift;
                   2516:     &viewgrades_js($request);
1.41      ng       2517: 
1.257     albertel 2518:     my ($symb,$url) = ($env{'form.symb'},$env{'form.url'}); 
1.168     albertel 2519:     #need to make sure we have the correct data for later EXT calls, 
                   2520:     #thus invalidate the cache
                   2521:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 2522:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   2523:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 2524:     &Apache::lonnet::clear_EXT_cache_status();
                   2525: 
1.167     sakharuk 2526:     my $result='<h3><font color="#339933">'.&mt('Manual Grading').'</font></h3>';
1.257     albertel 2527:     $result.='<font size=+1><b>Current Resource: </b>'.$env{'form.probTitle'}.'</font>'."\n";
1.41      ng       2528: 
                   2529:     #view individual student submission form - called using Javascript viewOneStudent
1.45      ng       2530:     $result.=&jscriptNform($url,$symb);
1.41      ng       2531: 
1.44      ng       2532:     #beginning of class grading form
1.41      ng       2533:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.106     albertel 2534: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.41      ng       2535: 	'<input type="hidden" name="url"     value="'.$url.'" />'."\n".
1.38      ng       2536: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.257     albertel 2537: 	'<input type="hidden" name="section" value="'.$env{'form.section'}.'" />'."\n".
                   2538: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   2539: 	'<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
                   2540: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       2541: 
1.126     ng       2542:     my $sectionClass;
1.257     albertel 2543:     if ($env{'form.section'} eq 'all') {
1.126     ng       2544: 	$sectionClass='Class </h3>';
1.257     albertel 2545:     } elsif ($env{'form.section'} eq 'none') {
1.126     ng       2546: 	$sectionClass='Students in no Section </h3>';
1.52      albertel 2547:     } else {
1.257     albertel 2548: 	$sectionClass='Students in Section '.$env{'form.section'}.'</h3>';
1.52      albertel 2549:     }
1.126     ng       2550:     $result.='<h3>Assign Common Grade To '.$sectionClass;
1.52      albertel 2551:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   2552: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       2553:     #radio buttons/text box for assigning points for a section or class.
                   2554:     #handles different parts of a problem
1.125     ng       2555:     my ($partlist,$handgrade) = &response_type($url,$symb);
1.42      ng       2556:     my %weight = ();
                   2557:     my $ctsparts = 0;
1.41      ng       2558:     $result.='<table border="0">';
1.45      ng       2559:     my %seen = ();
1.42      ng       2560:     for (sort keys(%$handgrade)) {
1.54      albertel 2561: 	my ($partid,$respid) = split (/_/,$_,2);
1.45      ng       2562: 	next if $seen{$partid};
                   2563: 	$seen{$partid}++;
1.147     albertel 2564: 	my $handgrade=$$handgrade{$_};
1.42      ng       2565: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   2566: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   2567: 
1.44      ng       2568: 	$result.='<input type="hidden" name="partid_'.
                   2569: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   2570: 	$result.='<input type="hidden" name="weight_'.
                   2571: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.207     albertel 2572: 	my $display_part=&get_display_part($partid,$url,$symb);
                   2573: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       2574: 	$result.='<table border="0"><tr>';  
1.41      ng       2575: 	my $ctr = 0;
1.42      ng       2576: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
                   2577: 	    $result.= '<td><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 2578: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.41      ng       2579: 		','.$ctr.')" />'.$ctr."</td>\n";
                   2580: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   2581: 	    $ctr++;
                   2582: 	}
                   2583: 	$result.='</tr></table>';
1.44      ng       2584: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 2585: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   2586: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       2587: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   2588: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 2589: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 2590: 		$weight{$partid}.')"> '.
1.42      ng       2591: 	    '<option selected="on"> </option>'.
1.125     ng       2592: 	    '<option>excused</option>'.
1.265     www      2593: 	    '<option>reset status</option></select></td>'.
1.266     albertel 2594:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       2595: 	$ctsparts++;
1.41      ng       2596:     }
1.52      albertel 2597:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   2598: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.42      ng       2599:     $result.='<input type="button" value="Reset" '.
1.111     ng       2600: 	'onClick="javascript:resetEntry('.$ctsparts.');" TARGET=_self>';
1.41      ng       2601: 
1.44      ng       2602:     #table listing all the students in a section/class
                   2603:     #header of table
1.126     ng       2604:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       2605:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       2606: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       2607: 	'<td>'.&nameUserString('header')."</td>\n";
1.146     albertel 2608:     my (@parts) = sort(&getpartlist($url,$symb));
1.269     raeburn  2609:     my @partids = ();
1.41      ng       2610:     foreach my $part (@parts) {
                   2611: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       2612: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       2613: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 2614: 	my ($partid) = &split_part_type($part);
1.269     raeburn  2615:         push(@partids, $partid);
1.207     albertel 2616: 	my $display_part=&get_display_part($partid,$url,$symb);
1.41      ng       2617: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 2618: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   2619: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       2620: 	    next;
1.207     albertel 2621: 	} else {
                   2622: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       2623: 	}
1.53      albertel 2624: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 2625: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       2626:     }
                   2627:     $result.='</tr>';
1.44      ng       2628: 
1.270     albertel 2629:     my %last_resets = 
                   2630: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  2631: 
1.41      ng       2632:     #get info for each student
1.44      ng       2633:     #list all the students - with points and grade status
1.257     albertel 2634:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       2635:     my $ctr = 0;
1.53      albertel 2636:     foreach (sort {lc($$fullname{$a}) cmp lc($$fullname{$b}) } keys %$fullname) {
1.126     ng       2637: 	$ctr++;
1.257     albertel 2638: 	$result.=&viewstudentgrade($url,$symb,$env{'request.course.id'},
1.269     raeburn  2639: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       2640:     }
                   2641:     $result.='</table></td></tr></table>';
                   2642:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       2643:     $result.='<input type="button" value="Save" '.
1.45      ng       2644: 	'onClick="javascript:submit();" TARGET=_self /></form>'."\n";
1.96      albertel 2645:     if (scalar(%$fullname) eq 0) {
                   2646: 	my $colspan=3+scalar(@parts);
1.257     albertel 2647: 	$result='<font color="red">There are no students in section "'.$env{'form.section'}.
                   2648: 	    '" with enrollment status "'.$env{'form.Status'}.'" to modify or grade.</font>';
1.96      albertel 2649:     }
1.41      ng       2650:     $result.=&show_grading_menu_form($symb,$url);
                   2651:     return $result;
                   2652: }
                   2653: 
1.44      ng       2654: #--- call by previous routine to display each student
1.41      ng       2655: sub viewstudentgrade {
1.269     raeburn  2656:     my ($url,$symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       2657:     my ($uname,$udom) = split(/:/,$student);
1.90      albertel 2658:     $student=~s/:/_/;
1.44      ng       2659:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  2660:     my %aggregates = (); 
1.233     albertel 2661:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   2662: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   2663: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       2664: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.112     ng       2665: 	'\')"; TARGET=_self>'.$fullname.'</a> '.
1.257     albertel 2666: 	'<font color="#999999">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</font></td>'."\n";
1.63      albertel 2667:     foreach my $apart (@$parts) {
                   2668: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       2669: 	my $score=$record{"resource.$part.$type"};
1.269     raeburn  2670:         $result.='<td align="middle">';
                   2671:         my ($aggtries,$totaltries);
                   2672:         unless (exists($aggregates{$part})) {
1.270     albertel 2673: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   2674: 
                   2675: 	    $aggtries = $totaltries;
1.269     raeburn  2676:             if ($$last_resets{$part}) {  
1.270     albertel 2677:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   2678: 					   $part);
                   2679:             }
1.269     raeburn  2680:             $result.='<input type="hidden" name="'.
                   2681:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   2682:             $result.='<input type="hidden" name="'.
                   2683:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   2684:             $aggregates{$part} = 1;
                   2685:         }
1.41      ng       2686: 	if ($type eq 'awarded') {
1.42      ng       2687: 	    my $pts = $score eq '' ? '' : $score*$$weight{$part};
                   2688: 	    $result.='<input type="hidden" name="'.
1.89      albertel 2689: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 2690: 	    $result.='<input type="text" name="'.
1.89      albertel 2691: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   2692: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       2693: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       2694: 	} elsif ($type eq 'solved') {
                   2695: 	    my ($status,$foo)=split(/_/,$score,2);
                   2696: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 2697: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 2698: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 2699: 	    $result.='&nbsp;<select name="'.
1.89      albertel 2700: 		'GD_'.$student.'_'.$part.'_solved" '.
                   2701: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.125     ng       2702: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="on">excused</option>' 
                   2703: 		: '<option selected="on"> </option><option>excused</option>')."\n";
                   2704: 	    $result.='<option>reset status</option>';
1.126     ng       2705: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       2706: 	} else {
                   2707: 	    $result.='<input type="hidden" name="'.
                   2708: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   2709: 		    "\n";
1.233     albertel 2710: 	    $result.='<input type="text" name="'.
1.122     ng       2711: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   2712: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       2713: 	}
                   2714:     }
                   2715:     $result.='</tr>';
                   2716:     return $result;
1.38      ng       2717: }
                   2718: 
1.44      ng       2719: #--- change scores for all the students in a section/class
                   2720: #    record does not get update if unchanged
1.38      ng       2721: sub editgrades {
1.41      ng       2722:     my ($request) = @_;
                   2723: 
1.257     albertel 2724:     my $symb=$env{'form.symb'};
                   2725:     my $url =$env{'form.url'};
1.45      ng       2726:     my $title='<h3><font color="#339933">Current Grade Status</font></h3>';
1.257     albertel 2727:     $title.='<font size=+1><b>Current Resource: </b>'.$env{'form.probTitle'}.'</font><br />'."\n";
                   2728:     $title.='<font size=+1><b>Section: </b>'.$env{'form.section'}.'</font>'."\n";
1.126     ng       2729: 
1.44      ng       2730:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       2731:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   2732: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   2733: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       2734: 
                   2735:     my %scoreptr = (
                   2736: 		    'correct'  =>'correct_by_override',
                   2737: 		    'incorrect'=>'incorrect_by_override',
                   2738: 		    'excused'  =>'excused',
                   2739: 		    'ungraded' =>'ungraded_attempted',
                   2740: 		    'nothing'  => '',
                   2741: 		    );
1.257     albertel 2742:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       2743: 
1.44      ng       2744:     my (@partid);
                   2745:     my %weight = ();
1.54      albertel 2746:     my %columns = ();
1.44      ng       2747:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 2748: 
1.146     albertel 2749:     my (@parts) = sort(&getpartlist($url,$symb));
1.54      albertel 2750:     my $header;
1.257     albertel 2751:     while ($ctr < $env{'form.totalparts'}) {
                   2752: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       2753: 	push @partid,$partid;
1.257     albertel 2754: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       2755: 	$ctr++;
1.54      albertel 2756:     }
                   2757:     foreach my $partid (@partid) {
                   2758: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   2759: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   2760: 	$columns{$partid}=2;
                   2761: 	foreach my $stores (@parts) {
                   2762: 	    my ($part,$type) = &split_part_type($stores);
                   2763: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   2764: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   2765: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   2766: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       2767: 	    $display =~ s/Number of Attempts/Tries/;
                   2768: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   2769: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 2770: 	    $columns{$partid}+=2;
                   2771: 	}
                   2772:     }
                   2773:     foreach my $partid (@partid) {
1.207     albertel 2774: 	my $display_part=&get_display_part($partid,$url,$symb);
1.54      albertel 2775: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 2776: 	    '" align="center"><b>Part:</b> '.$display_part.
                   2777: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 2778: 
1.44      ng       2779:     }
                   2780:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 2781:     $result .= $header;
1.44      ng       2782:     $result .= '</tr>'."\n";
1.93      albertel 2783:     my $noupdate;
1.126     ng       2784:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 2785:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 2786: 	my $line;
1.257     albertel 2787: 	my $user = $env{'form.ctr'.$i};
1.92      albertel 2788: 	my $usercolon = $user;
                   2789: 	$usercolon =~s/_/:/;
                   2790: 	my ($uname,$udom)=split(/_/,$user);
1.44      ng       2791: 	my %newrecord;
                   2792: 	my $updateflag = 0;
1.129     ng       2793: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$usercolon},$uname,$udom).'</td>';
1.108     albertel 2794: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 2795: 	if (!&canmodify($usec)) {
1.126     ng       2796: 	    my $numcols=scalar(@partid)*4+2;
1.105     albertel 2797: 	    $noupdate.=$line."<td colspan=\"$numcols\"><font color=\"red\">Not allowed to modify student</font></td></tr>";
                   2798: 	    next;
                   2799: 	}
1.269     raeburn  2800:         my %aggregate = ();
                   2801:         my $aggregateflag = 0;
1.44      ng       2802: 	foreach (@partid) {
1.257     albertel 2803: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 2804: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   2805: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 2806: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   2807: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 2808: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   2809: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       2810: 	    my $score;
                   2811: 	    if ($partial eq '') {
1.257     albertel 2812: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       2813: 	    } elsif ($partial > 0) {
                   2814: 		$score = 'correct_by_override';
                   2815: 	    } elsif ($partial == 0) {
                   2816: 		$score = 'incorrect_by_override';
                   2817: 	    }
1.257     albertel 2818: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       2819: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   2820: 
                   2821: 	    if ($dropMenu eq 'reset status' &&
                   2822: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
                   2823: 		$newrecord{'resource.'.$_.'.tries'} = 0;
                   2824: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   2825: 		$newrecord{'resource.'.$_.'.award'} = '';
                   2826: 		$newrecord{'resource.'.$_.'.awarded'} = 0;
1.257     albertel 2827: 		$newrecord{'resource.'.$_.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.125     ng       2828: 		$updateflag = 1;
1.269     raeburn  2829:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   2830:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   2831:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   2832:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   2833:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   2834:                     $aggregateflag = 1;
                   2835:                 }
1.139     albertel 2836: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   2837: 		$updateflag = 1;
                   2838: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   2839: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   2840: 		$rec_update++;
1.125     ng       2841: 	    }
                   2842: 
1.93      albertel 2843: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       2844: 		'<td align="center">'.$awarded.
                   2845: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 2846: 
1.54      albertel 2847: 
                   2848: 	    my $partid=$_;
                   2849: 	    foreach my $stores (@parts) {
                   2850: 		my ($part,$type) = &split_part_type($stores);
                   2851: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   2852: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 2853: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   2854: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 2855: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   2856: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 2857: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 2858: 		    $updateflag=1;
                   2859: 		}
1.93      albertel 2860: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 2861: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   2862: 	    }
1.44      ng       2863: 	}
1.93      albertel 2864: 	$line.='</tr>'."\n";
1.44      ng       2865: 	if ($updateflag) {
                   2866: 	    $count++;
1.257     albertel 2867: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 2868: 				    $udom,$uname);
1.126     ng       2869: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   2870: 	    $updateCtr++;
1.93      albertel 2871: 	} else {
1.126     ng       2872: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   2873: 	    $noupdateCtr++;
1.44      ng       2874: 	}
1.269     raeburn  2875:         if ($aggregateflag) {
                   2876:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   2877:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2878:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   2879:         }
1.93      albertel 2880:     }
                   2881:     if ($noupdate) {
1.126     ng       2882: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   2883: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 2884: 	$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       2885:     }
1.72      ng       2886:     $result .= '</table></td></tr></table>'."\n".
                   2887: 	&show_grading_menu_form ($symb,$url);
1.125     ng       2888:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       2889: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 2890: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       2891:     return $title.$msg.$result;
1.5       albertel 2892: }
1.54      albertel 2893: 
                   2894: sub split_part_type {
                   2895:     my ($partstr) = @_;
                   2896:     my ($temp,@allparts)=split(/_/,$partstr);
                   2897:     my $type=pop(@allparts);
                   2898:     my $part=join('.',@allparts);
                   2899:     return ($part,$type);
                   2900: }
                   2901: 
1.44      ng       2902: #------------- end of section for handling grading by section/class ---------
                   2903: #
                   2904: #----------------------------------------------------------------------------
                   2905: 
1.5       albertel 2906: 
1.44      ng       2907: #----------------------------------------------------------------------------
                   2908: #
                   2909: #-------------------------- Next few routines handles grading by csv upload
                   2910: #
                   2911: #--- Javascript to handle csv upload
1.27      albertel 2912: sub csvupload_javascript_reverse_associate {
1.246     albertel 2913:     my $error1=&mt('You need to specify the username or ID');
                   2914:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 2915:   return(<<ENDPICK);
                   2916:   function verify(vf) {
                   2917:     var foundsomething=0;
                   2918:     var founduname=0;
1.243     albertel 2919:     var foundID=0;
1.27      albertel 2920:     for (i=0;i<=vf.nfields.value;i++) {
                   2921:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 2922:       if (i==0 && tw!=0) { foundID=1; }
                   2923:       if (i==1 && tw!=0) { founduname=1; }
                   2924:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 2925:     }
1.246     albertel 2926:     if (founduname==0 && foundID==0) {
                   2927: 	alert('$error1');
                   2928: 	return;
1.27      albertel 2929:     }
                   2930:     if (foundsomething==0) {
1.246     albertel 2931: 	alert('$error2');
                   2932: 	return;
1.27      albertel 2933:     }
                   2934:     vf.submit();
                   2935:   }
                   2936:   function flip(vf,tf) {
                   2937:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   2938:     var i;
                   2939:     for (i=0;i<=vf.nfields.value;i++) {
                   2940:       //can not pick the same destination field for both name and domain
                   2941:       if (((i ==0)||(i ==1)) && 
                   2942:           ((tf==0)||(tf==1)) && 
                   2943:           (i!=tf) &&
                   2944:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   2945:         eval('vf.f'+i+'.selectedIndex=0;')
                   2946:       }
                   2947:     }
                   2948:   }
                   2949: ENDPICK
                   2950: }
                   2951: 
                   2952: sub csvupload_javascript_forward_associate {
1.246     albertel 2953:     my $error1=&mt('You need to specify the username or ID');
                   2954:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 2955:   return(<<ENDPICK);
                   2956:   function verify(vf) {
                   2957:     var foundsomething=0;
                   2958:     var founduname=0;
1.243     albertel 2959:     var foundID=0;
1.27      albertel 2960:     for (i=0;i<=vf.nfields.value;i++) {
                   2961:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 2962:       if (tw==1) { foundID=1; }
                   2963:       if (tw==2) { founduname=1; }
                   2964:       if (tw>3) { foundsomething=1; }
1.27      albertel 2965:     }
1.246     albertel 2966:     if (founduname==0 && foundID==0) {
                   2967: 	alert('$error1');
                   2968: 	return;
1.27      albertel 2969:     }
                   2970:     if (foundsomething==0) {
1.246     albertel 2971: 	alert('$error2');
                   2972: 	return;
1.27      albertel 2973:     }
                   2974:     vf.submit();
                   2975:   }
                   2976:   function flip(vf,tf) {
                   2977:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   2978:     var i;
                   2979:     //can not pick the same destination field twice
                   2980:     for (i=0;i<=vf.nfields.value;i++) {
                   2981:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   2982:         eval('vf.f'+i+'.selectedIndex=0;')
                   2983:       }
                   2984:     }
                   2985:   }
                   2986: ENDPICK
                   2987: }
                   2988: 
1.26      albertel 2989: sub csvuploadmap_header {
1.41      ng       2990:     my ($request,$symb,$url,$datatoken,$distotal)= @_;
                   2991:     my $javascript;
1.257     albertel 2992:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       2993: 	$javascript=&csvupload_javascript_reverse_associate();
                   2994:     } else {
                   2995: 	$javascript=&csvupload_javascript_forward_associate();
                   2996:     }
1.45      ng       2997: 
1.257     albertel 2998:     my ($result) = &showResourceInfo($url,$env{'form.probTitle'});
                   2999:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3000:     my $ignore=&mt('Ignore First Line');
1.41      ng       3001:     $request->print(<<ENDPICK);
1.26      albertel 3002: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.45      ng       3003: <h3><font color="#339933">Uploading Class Grades</font></h3>
                   3004: $result
1.26      albertel 3005: <hr>
                   3006: <h3>Identify fields</h3>
                   3007: Total number of records found in file: $distotal <hr />
                   3008: Enter as many fields as you can. The system will inform you and bring you back
                   3009: to this page if the data selected is insufficient to run your class.<hr />
                   3010: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3011: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3012: <input type="hidden" name="associate"  value="" />
                   3013: <input type="hidden" name="phase"      value="three" />
                   3014: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3015: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3016: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3017: <input type="hidden" name="upfile_associate" 
1.257     albertel 3018:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3019: <input type="hidden" name="symb"       value="$symb" />
                   3020: <input type="hidden" name="url"        value="$url" />
1.257     albertel 3021: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3022: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3023: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3024: <hr />
                   3025: <script type="text/javascript" language="Javascript">
                   3026: $javascript
                   3027: </script>
                   3028: ENDPICK
1.118     ng       3029:     return '';
1.26      albertel 3030: 
                   3031: }
                   3032: 
                   3033: sub csvupload_fields {
1.146     albertel 3034:     my ($url,$symb) = @_;
                   3035:     my (@parts) = &getpartlist($url,$symb);
1.243     albertel 3036:     my @fields=(['ID','Student ID'],
                   3037: 		['username','Student Username'],
                   3038: 		['domain','Student Domain']);
1.41      ng       3039:     foreach my $part (sort(@parts)) {
                   3040: 	my @datum;
                   3041: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3042: 	my $name=$part;
                   3043: 	if  (!$display) { $display = $name; }
                   3044: 	@datum=($name,$display);
1.244     albertel 3045: 	if ($name=~/^stores_(.*)_awarded/) {
                   3046: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3047: 	}
1.41      ng       3048: 	push(@fields,\@datum);
                   3049:     }
                   3050:     return (@fields);
1.26      albertel 3051: }
                   3052: 
                   3053: sub csvuploadmap_footer {
1.41      ng       3054:     my ($request,$i,$keyfields) =@_;
                   3055:     $request->print(<<ENDPICK);
1.26      albertel 3056: </table>
                   3057: <input type="hidden" name="nfields" value="$i" />
                   3058: <input type="hidden" name="keyfields" value="$keyfields" />
                   3059: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3060: </form>
                   3061: ENDPICK
                   3062: }
                   3063: 
1.86      ng       3064: sub upcsvScores_form {
                   3065:     my ($request) = shift;
                   3066:     my ($symb,$url)=&get_symb_and_url($request);
                   3067:     if (!$symb) {return '';}
                   3068:     my $result =<<CSVFORMJS;
                   3069: <script type="text/javascript" language="javascript">
                   3070:     function checkUpload(formname) {
                   3071: 	if (formname.upfile.value == "") {
                   3072: 	    alert("Please use the browse button to select a file from your local directory.");
                   3073: 	    return false;
                   3074: 	}
                   3075: 	formname.submit();
                   3076:     }
                   3077:     </script>
                   3078: CSVFORMJS
1.257     albertel 3079:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   3080:     my ($table) = &showResourceInfo($url,$env{'form.probTitle'});
1.118     ng       3081:     $result.=$table;
1.86      ng       3082:     $result.='<br /><table width=100% border=0><tr><td bgcolor="#777777">'."\n";
                   3083:     $result.='<table width=100% border=0><tr bgcolor="#e6ffff"><td>'."\n";
1.118     ng       3084:     $result.='&nbsp;<b>Specify a file containing the class scores for current resource'.
1.86      ng       3085: 	'.</b></td></tr>'."\n";
                   3086:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
                   3087:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3088:     my $ignore=&mt('Ignore First Line');
1.86      ng       3089:     $result.=<<ENDUPFORM;
1.106     albertel 3090: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3091: <input type="hidden" name="symb" value="$symb" />
                   3092: <input type="hidden" name="url" value="$url" />
                   3093: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3094: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3095: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3096: $upfile_select
                   3097: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scores" />
1.245     albertel 3098: <label><input type="checkbox" name="noFirstLine" />$ignore</lable>
1.86      ng       3099: </form>
                   3100: ENDUPFORM
                   3101:     $result.='</td></tr></table>'."\n";
                   3102:     $result.='</td></tr></table><br /><br />'."\n";
                   3103:     $result.=&show_grading_menu_form($symb,$url);
                   3104:     return $result;
                   3105: }
                   3106: 
                   3107: 
1.26      albertel 3108: sub csvuploadmap {
1.41      ng       3109:     my ($request)= @_;
                   3110:     my ($symb,$url)=&get_symb_and_url($request);
                   3111:     if (!$symb) {return '';}
1.72      ng       3112: 
1.41      ng       3113:     my $datatoken;
1.257     albertel 3114:     if (!$env{'form.datatoken'}) {
1.41      ng       3115: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3116:     } else {
1.257     albertel 3117: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3118: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3119:     }
1.41      ng       3120:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3121:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.41      ng       3122:     &csvuploadmap_header($request,$symb,$url,$datatoken,$#records+1);
                   3123:     my ($i,$keyfields);
                   3124:     if (@records) {
1.146     albertel 3125: 	my @fields=&csvupload_fields($url,$symb);
1.45      ng       3126: 
1.257     albertel 3127: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3128: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3129: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3130: 							  \@fields);
                   3131: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3132: 	    chop($keyfields);
                   3133: 	} else {
                   3134: 	    unshift(@fields,['none','']);
                   3135: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3136: 							    \@fields);
                   3137: 	    my %sone=&Apache::loncommon::record_sep($records[0]);
                   3138: 	    $keyfields=join(',',sort(keys(%sone)));
                   3139: 	}
                   3140:     }
                   3141:     &csvuploadmap_footer($request,$i,$keyfields);
1.72      ng       3142:     $request->print(&show_grading_menu_form($symb,$url));
                   3143: 
1.41      ng       3144:     return '';
1.27      albertel 3145: }
                   3146: 
1.246     albertel 3147: sub csvuploadoptions {
1.41      ng       3148:     my ($request)= @_;
                   3149:     my ($symb,$url)=&get_symb_and_url($request);
1.257     albertel 3150:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3151:     my $ignore=&mt('Ignore First Line');
                   3152:     $request->print(<<ENDPICK);
                   3153: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   3154: <h3><font color="#339933">Uploading Class Grade Options</font></h3>
                   3155: <input type="hidden" name="command"    value="csvuploadassign" />
                   3156: <input type="submit" value="Assign Grades" /><br />
                   3157: <p>
                   3158: <label>
                   3159:    <input type="checkbox" name="show_full_results" />
                   3160:    Show a table of all changes
                   3161: </label>
                   3162: </p>
                   3163: <p>
                   3164: <label>
                   3165:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3166:    Overwrite any existing score
                   3167: </label>
                   3168: </p>
                   3169: ENDPICK
                   3170:     my %fields=&get_fields();
                   3171:     if (!defined($fields{'domain'})) {
1.257     albertel 3172: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3173: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3174:     }
1.257     albertel 3175:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3176: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3177: 	my $cleankey=$1;
                   3178: 	if ($cleankey eq 'command') { next; }
                   3179: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3180: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3181:     }
                   3182:     # FIXME do a check for any duplicated user ids...
                   3183:     # FIXME do a check for any invalid user ids?...
                   3184:     $request->print("<hr /></form>\n");
                   3185:     $request->print(&show_grading_menu_form($symb,$url));
                   3186:     return '';
                   3187: }
                   3188: 
                   3189: sub get_fields {
                   3190:     my %fields;
1.257     albertel 3191:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3192:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3193: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3194: 	    if ($env{'form.f'.$i} ne 'none') {
                   3195: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3196: 	    }
                   3197: 	} else {
1.257     albertel 3198: 	    if ($env{'form.f'.$i} ne 'none') {
                   3199: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3200: 	    }
                   3201: 	}
1.27      albertel 3202:     }
1.246     albertel 3203:     return %fields;
                   3204: }
                   3205: 
                   3206: sub csvuploadassign {
                   3207:     my ($request)= @_;
                   3208:     my ($symb,$url)=&get_symb_and_url($request);
                   3209:     if (!$symb) {return '';}
                   3210:     &Apache::loncommon::load_tmp_file($request);
                   3211:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3212:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3213:     my %fields=&get_fields();
1.41      ng       3214:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3215:     my $courseid=$env{'request.course.id'};
1.97      albertel 3216:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3217:     my @notallowed;
1.41      ng       3218:     my @skipped;
                   3219:     my $countdone=0;
                   3220:     foreach my $grade (@gradedata) {
                   3221: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3222: 	my $domain;
                   3223: 	if ($entries{$fields{'domain'}}) {
                   3224: 	    $domain=$entries{$fields{'domain'}};
                   3225: 	} else {
1.257     albertel 3226: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3227: 	}
1.243     albertel 3228: 	$domain=~s/\s//g;
1.41      ng       3229: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3230: 	$username=~s/\s//g;
1.243     albertel 3231: 	if (!$username) {
                   3232: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3233: 	    $id=~s/\s//g;
1.243     albertel 3234: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3235: 	    $username=$ids{$id};
                   3236: 	}
1.41      ng       3237: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3238: 	    my $id=$entries{$fields{'ID'}};
                   3239: 	    $id=~s/\s//g;
                   3240: 	    if ($id) {
                   3241: 		push(@skipped,"$id:$domain");
                   3242: 	    } else {
                   3243: 		push(@skipped,"$username:$domain");
                   3244: 	    }
1.41      ng       3245: 	    next;
                   3246: 	}
1.108     albertel 3247: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3248: 	if (!&canmodify($usec)) {
                   3249: 	    push(@notallowed,"$username:$domain");
                   3250: 	    next;
                   3251: 	}
1.244     albertel 3252: 	my %points;
1.41      ng       3253: 	my %grades;
                   3254: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3255: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3256: 		$dest eq 'domain') { next; }
                   3257: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3258: 	    if ($dest=~/stores_(.*)_points/) {
                   3259: 		my $part=$1;
                   3260: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3261: 					      $symb,$domain,$username);
1.247     albertel 3262: 		$entries{$fields{$dest}}=~s/\s//g;
1.244     albertel 3263: 		my $pcr=$entries{$fields{$dest}} / $wgt;
                   3264: 		my $award='correct_by_override';
                   3265: 		$grades{"resource.$part.awarded"}=$pcr;
                   3266: 		$grades{"resource.$part.solved"}=$award;
                   3267: 		$points{$part}=1;
                   3268: 	    } else {
                   3269: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3270: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3271: 		my $store_key=$dest;
                   3272: 		$store_key=~s/^stores/resource/;
                   3273: 		$store_key=~s/_/\./g;
                   3274: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3275: 	    }
1.41      ng       3276: 	}
1.244     albertel 3277: 	if (! %grades) { push(@skipped,"$username:$domain no data to store"); }
1.257     albertel 3278: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.244     albertel 3279: #	&Apache::lonnet::logthis(" storing ".(join('-',%grades)));
1.257     albertel 3280: 	&Apache::lonnet::cstore(\%grades,$symb,$env{'request.course.id'},
1.41      ng       3281: 				$domain,$username);
                   3282: 	$request->print('.');
                   3283: 	$request->rflush();
                   3284: 	$countdone++;
                   3285:     }
                   3286:     $request->print("<br />Stored $countdone students\n");
                   3287:     if (@skipped) {
1.106     albertel 3288: 	$request->print('<p<font size="+1"><b>Skipped Students</b></font></p>');
                   3289: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3290:     }
                   3291:     if (@notallowed) {
                   3292: 	$request->print('<p><font size="+1" color="red"><b>Students Not Allowed to Modify</b></font></p>');
                   3293: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3294:     }
1.106     albertel 3295:     $request->print("<br />\n");
1.41      ng       3296:     $request->print(&show_grading_menu_form($symb,$url));
                   3297:     return '';
1.26      albertel 3298: }
1.44      ng       3299: #------------- end of section for handling csv file upload ---------
                   3300: #
                   3301: #-------------------------------------------------------------------
                   3302: #
1.122     ng       3303: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3304: #
                   3305: #--- Select a page/sequence and a student to grade
1.68      ng       3306: sub pickStudentPage {
                   3307:     my ($request) = shift;
                   3308: 
                   3309:     $request->print(<<LISTJAVASCRIPT);
                   3310: <script type="text/javascript" language="javascript">
                   3311: 
                   3312: function checkPickOne(formname) {
1.76      ng       3313:     if (radioSelection(formname.student) == null) {
1.68      ng       3314: 	alert("Please select the student you wish to grade.");
                   3315: 	return;
                   3316:     }
1.125     ng       3317:     ptr = pullDownSelection(formname.selectpage);
                   3318:     formname.page.value = formname["page"+ptr].value;
                   3319:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3320:     formname.submit();
                   3321: }
                   3322: 
                   3323: </script>
                   3324: LISTJAVASCRIPT
1.118     ng       3325:     &commonJSfunctions($request);
1.72      ng       3326:     my ($symb,$url) = &get_symb_and_url($request);
1.257     albertel 3327:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3328:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3329:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3330: 
                   3331:     my $result='<h3><font color="#339933">&nbsp;'.
                   3332: 	'Manual Grading by Page or Sequence</font></h3>';
                   3333: 
1.80      ng       3334:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3335:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.74      albertel 3336:     my ($titles,$symbx) = &getSymbMap($request);
1.137     albertel 3337:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3338: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3339: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3340:     my $ctr=0;
1.68      ng       3341:     foreach (@$titles) {
                   3342: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3343: 	$result.='<option value="'.$ctr.'" '.
1.71      ng       3344: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="on"' : '').
                   3345: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3346: 	$ctr++;
1.68      ng       3347:     }
                   3348:     $result.= '</select>'."<br>\n";
1.70      ng       3349:     $ctr=0;
                   3350:     foreach (@$titles) {
                   3351: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3352: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3353: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3354: 	$ctr++;
                   3355:     }
1.72      ng       3356:     $result.='<input type="hidden" name="page" />'."\n".
                   3357: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3358: 
1.144     albertel 3359:     $result.='&nbsp;<b>View Problems Text: </b><input type="radio" name="vProb" value="no" checked="on" /> no '."\n".
1.71      ng       3360: 	'<input type="radio" name="vProb" value="yes" /> yes '."<br>\n";
1.72      ng       3361: 
1.71      ng       3362:     $result.='&nbsp;<b>Submission Details: </b>'.
                   3363: 	'<input type="radio" name="lastSub" value="none" /> none'."\n".
1.122     ng       3364: 	'<input type="radio" name="lastSub" value="datesub" checked /> by dates and submissions'."\n".
1.71      ng       3365: 	'<input type="radio" name="lastSub" value="all" /> all details'."\n";
1.72      ng       3366: 
1.68      ng       3367:     $result.='<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
1.257     albertel 3368: 	'<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.72      ng       3369: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
                   3370: 	'<input type="hidden" name="url"     value="'.$url.'" />'."\n".
1.80      ng       3371: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.257     albertel 3372: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       3373: 
1.80      ng       3374:     $result.='&nbsp;<input type="button" '.
1.126     ng       3375: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       3376: 
1.68      ng       3377:     $request->print($result);
                   3378: 
1.126     ng       3379:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br>'.
1.68      ng       3380: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3381: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       3382: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3383: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       3384: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3385: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       3386:  
1.76      ng       3387:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       3388:     my $ptr = 1;
                   3389:     foreach my $student (sort {lc($$fullname{$a}) cmp lc($$fullname{$b}) } keys %$fullname) {
                   3390: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       3391: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   3392: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.129     ng       3393: 	$studentTable.='<td>&nbsp;<input type="radio" name="student" value="'.$student.'" /> '
                   3394: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."\n";
1.126     ng       3395: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       3396: 	$ptr++;
                   3397:     }
1.126     ng       3398:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;' if ($ptr%2 == 0);
1.68      ng       3399:     $studentTable.='</td></tr></table></td></tr></table>'."\n";
1.126     ng       3400:     $studentTable.='<input type="button" '.
                   3401: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       3402: 
                   3403:     $studentTable.=&show_grading_menu_form($symb,$url);
                   3404:     $request->print($studentTable);
                   3405: 
                   3406:     return '';
                   3407: }
                   3408: 
                   3409: sub getSymbMap {
1.74      albertel 3410:     my ($request) = @_;
1.132     bowersj2 3411:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       3412: 
                   3413:     my %symbx = ();
                   3414:     my @titles = ();
1.117     bowersj2 3415:     my $minder = 0;
                   3416: 
                   3417:     # Gather every sequence that has problems.
1.240     albertel 3418:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   3419: 					       1,0,1);
1.117     bowersj2 3420:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 3421: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.117     bowersj2 3422: 	    my $title = $minder.'.'.$sequence->compTitle();
                   3423: 	    push @titles, $title; # minder in case two titles are identical
                   3424: 	    $symbx{$title} = $sequence->symb();
                   3425: 	    $minder++;
1.241     albertel 3426: 	}
1.68      ng       3427:     }
                   3428:     return \@titles,\%symbx;
                   3429: }
                   3430: 
1.72      ng       3431: #
                   3432: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       3433: sub displayPage {
                   3434:     my ($request) = shift;
                   3435: 
1.72      ng       3436:     my ($symb,$url) = &get_symb_and_url($request);
1.257     albertel 3437:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3438:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3439:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3440:     my $pageTitle = $env{'form.page'};
1.103     albertel 3441:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 3442:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   3443:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 3444: 
                   3445:     #need to make sure we have the correct data for later EXT calls, 
                   3446:     #thus invalidate the cache
                   3447:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3448:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3449:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3450:     &Apache::lonnet::clear_EXT_cache_status();
                   3451: 
1.103     albertel 3452:     if (!&canview($usec)) {
1.257     albertel 3453: 	$request->print('<font color="red">Unable to view requested student.('.$env{'form.student'}.')</font>');
1.103     albertel 3454: 	$request->print(&show_grading_menu_form($symb,$url));
                   3455: 	return;
                   3456:     }
1.257     albertel 3457:     my $result='<h3><font color="#339933">&nbsp;'.$env{'form.title'}.'</font></h3>';
                   3458:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       3459: 	'</h3>'."\n";
1.71      ng       3460:     &sub_page_js($request);
                   3461:     $request->print($result);
                   3462: 
1.132     bowersj2 3463:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 3464:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       3465:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
                   3466: 
                   3467:     my $iterator = $navmap->getIterator($map->map_start(),
                   3468: 					$map->map_finish());
                   3469: 
1.71      ng       3470:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       3471: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 3472: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   3473: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       3474: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 3475: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.72      ng       3476: 	'<input type="hidden" name="url"     value="'.$url.'" />'."\n".
                   3477: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.125     ng       3478: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 3479: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       3480: 
                   3481:     my $checkIcon = '<img src="'.$request->dir_config('lonIconsURL').
                   3482: 	'/check.gif" height="16" border="0" />';
                   3483: 
1.118     ng       3484:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   3485: 	' symbol.'."\n".
1.71      ng       3486: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3487: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       3488: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 3489: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       3490: 
1.196     albertel 3491:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       3492:     $iterator->next(); # skip the first BEGIN_MAP
                   3493:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 3494:     while ($depth > 0) {
1.68      ng       3495:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 3496:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       3497: 
1.235     albertel 3498:         if (ref($curRes) && $curRes->is_problem() && !$curRes->randomout) {
1.91      albertel 3499: 	    my $parts = $curRes->parts();
1.68      ng       3500:             my $title = $curRes->compTitle();
1.71      ng       3501: 	    my $symbx = $curRes->symb();
1.196     albertel 3502: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.71      ng       3503: 		(scalar(@{$parts}) == 1 ? '' : '<br>('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
                   3504: 	    $studentTable.='<td valign="top">';
1.257     albertel 3505: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 3506: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   3507: 					     undef,'both');
1.71      ng       3508: 	    } else {
1.257     albertel 3509: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'});
1.80      ng       3510: 		$companswer =~ s|<form(.*?)>||g;
                   3511: 		$companswer =~ s|</form>||g;
1.71      ng       3512: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       3513: #		    $companswer =~ s/$1/ /ms;
                   3514: #		    $request->print('match='.$1."<br>\n");
1.71      ng       3515: #		}
1.116     ng       3516: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.71      ng       3517: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br>&nbsp;<b>Correct answer:</b><br>'.$companswer;
                   3518: 	    }
                   3519: 
1.257     albertel 3520: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       3521: 
1.257     albertel 3522: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       3523: 		if ($record{'version'} eq '') {
                   3524: 		    $studentTable.='<br />&nbsp;<font color="red">No recorded submission for this problem</font><br />';
                   3525: 		} else {
1.116     ng       3526: 		    my %responseType = ();
                   3527: 		    foreach my $partid (@{$parts}) {
1.147     albertel 3528: 			my @responseIds =$curRes->responseIds($partid);
                   3529: 			my @responseType =$curRes->responseType($partid);
                   3530: 			my %responseIds;
                   3531: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   3532: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   3533: 			}
                   3534: 			$responseType{$partid} = \%responseIds;
1.116     ng       3535: 		    }
1.148     albertel 3536: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 3537: 
1.71      ng       3538: 		}
1.257     albertel 3539: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   3540: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       3541: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 3542: 									$env{'request.course.id'},
1.71      ng       3543: 									'','.submission');
                   3544:  
                   3545: 	    }
1.103     albertel 3546: 	    if (&canmodify($usec)) {
                   3547: 		foreach my $partid (@{$parts}) {
                   3548: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   3549: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   3550: 		    $question++;
                   3551: 		}
1.196     albertel 3552: 		$prob++;
1.71      ng       3553: 	    }
                   3554: 	    $studentTable.='</td></tr>';
1.68      ng       3555: 
1.103     albertel 3556: 	}
1.68      ng       3557:         $curRes = $iterator->next();
                   3558:     }
                   3559: 
1.71      ng       3560:     $studentTable.='</td></tr></table></td></tr></table>'."\n".
1.125     ng       3561: 	'<input type="button" value="Save" '.
1.71      ng       3562: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" TARGET=_self />'.
                   3563: 	'</form>'."\n";
                   3564:     $studentTable.=&show_grading_menu_form($symb,$url);
                   3565:     $request->print($studentTable);
                   3566: 
                   3567:     return '';
1.119     ng       3568: }
                   3569: 
                   3570: sub displaySubByDates {
1.148     albertel 3571:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 3572:     my $isCODE=0;
                   3573:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       3574:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   3575: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   3576: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 3577: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       3578: 	'<td><b>Submission</b></td>'.
                   3579: 	'<td><b>Status&nbsp;</b></td></tr>';
                   3580:     my ($version);
                   3581:     my %mark;
1.148     albertel 3582:     my %orders;
1.119     ng       3583:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 3584:     if (!exists($$record{'1:timestamp'})) {
                   3585: 	return '<br />&nbsp;<font color="red">Nothing submitted - no attempts</font><br />';
                   3586:     }
1.119     ng       3587:     for ($version=1;$version<=$$record{'version'};$version++) {
                   3588: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
                   3589: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 3590: 	if ($isCODE) {
                   3591: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   3592: 	}
1.119     ng       3593: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   3594: 	my @displaySub = ();
                   3595: 	foreach my $partid (@{$parts}) {
1.147     albertel 3596: 	    my @matchKey = sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys);
1.122     ng       3597: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.207     albertel 3598: 	    my $display_part=&get_display_part($partid,undef,$symb);
1.147     albertel 3599: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 3600: 		if (exists($$record{$version.':'.$matchKey}) &&
                   3601: 		    $$record{$version.':'.$matchKey} ne '') {
1.147     albertel 3602: 		    my ($responseId)=($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/);
1.207     albertel 3603: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.147     albertel 3604: 		    $displaySub[0].='<font color="#999999">(ID&nbsp;'.
1.207     albertel 3605: 			$responseId.')</font>&nbsp;<b>';
1.147     albertel 3606: 		    if ($$record{"$version:resource.$partid.tries"} eq '') {
                   3607: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   3608: 		    } else {
                   3609: 			$displaySub[0].='Trial&nbsp;'.
                   3610: 			    $$record{"$version:resource.$partid.tries"};
                   3611: 		    }
                   3612: 		    my $responseType=$responseType->{$partid}->{$responseId};
1.148     albertel 3613: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   3614: 		    if (!exists($orders{$partid}->{$responseId})) {
                   3615: 			$orders{$partid}->{$responseId}=
                   3616: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   3617: 		    }
1.147     albertel 3618: 		    $displaySub[0].='</b>&nbsp; '.
1.148     albertel 3619: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:").'<br />';
1.147     albertel 3620: 		}
                   3621: 	    }
                   3622: 	    if (exists $$record{"$version:resource.$partid.award"}) {
1.207     albertel 3623: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.147     albertel 3624: 		    lc($$record{"$version:resource.$partid.award"}).' '.
                   3625: 		    $mark{$$record{"$version:resource.$partid.solved"}}.
                   3626: 		    '<br />';
                   3627: 	    }
                   3628: 	    if (exists $$record{"$version:resource.$partid.regrader"}) {
                   3629: 		$displaySub[2].=$$record{"$version:resource.$partid.regrader"}.
1.207     albertel 3630: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 3631: 	    }
                   3632: 	}
                   3633: 	# needed because old essay regrader has not parts info
                   3634: 	if (exists $$record{"$version:resource.regrader"}) {
                   3635: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   3636: 	}
                   3637: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   3638: 	if ($displaySub[2]) {
                   3639: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   3640: 	}
                   3641: 	$studentTable.='&nbsp;</td></tr>';
                   3642:     
1.119     ng       3643:     }
                   3644:     $studentTable.='</table></td></tr></table>';
                   3645:     return $studentTable;
1.71      ng       3646: }
                   3647: 
                   3648: sub updateGradeByPage {
                   3649:     my ($request) = shift;
                   3650: 
1.257     albertel 3651:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3652:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3653:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3654:     my $pageTitle = $env{'form.page'};
1.103     albertel 3655:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 3656:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   3657:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 3658:     if (!&canmodify($usec)) {
1.257     albertel 3659: 	$request->print('<font color="red">Unable to modify requested student.('.$env{'form.student'}.'</font>');
                   3660: 	$request->print(&show_grading_menu_form($env{'form.symb'},$env{'form.url'}));
1.103     albertel 3661: 	return;
                   3662:     }
1.257     albertel 3663:     my $result='<h3><font color="#339933">&nbsp;'.$env{'form.title'}.'</font></h3>';
                   3664:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       3665: 	'</h3>'."\n";
1.70      ng       3666: 
1.68      ng       3667:     $request->print($result);
                   3668: 
1.132     bowersj2 3669:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 3670:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       3671:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
                   3672: 
                   3673:     my $iterator = $navmap->getIterator($map->map_start(),
                   3674: 					$map->map_finish());
1.70      ng       3675: 
1.71      ng       3676:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       3677: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       3678: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       3679: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   3680: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   3681: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   3682: 
                   3683:     $iterator->next(); # skip the first BEGIN_MAP
                   3684:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 3685:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 3686:     while ($depth > 0) {
1.71      ng       3687:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 3688:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       3689: 
                   3690:         if (ref($curRes) && $curRes->is_problem() && !$curRes->randomout) {
1.91      albertel 3691: 	    my $parts = $curRes->parts();
1.71      ng       3692:             my $title = $curRes->compTitle();
                   3693: 	    my $symbx = $curRes->symb();
1.196     albertel 3694: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.71      ng       3695: 		(scalar(@{$parts}) == 1 ? '' : '<br>('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
                   3696: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   3697: 
                   3698: 	    my %newrecord=();
                   3699: 	    my @displayPts=();
1.269     raeburn  3700:             my %aggregate = ();
                   3701:             my $aggregateflag = 0;
1.71      ng       3702: 	    foreach my $partid (@{$parts}) {
1.257     albertel 3703: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   3704: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       3705: 
1.257     albertel 3706: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   3707: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       3708: 		my $partial = $newpts/$wgt;
                   3709: 		my $score;
                   3710: 		if ($partial > 0) {
                   3711: 		    $score = 'correct_by_override';
1.125     ng       3712: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       3713: 		    $score = 'incorrect_by_override';
                   3714: 		}
1.257     albertel 3715: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       3716: 		if ($dropMenu eq 'excused') {
1.71      ng       3717: 		    $partial = '';
                   3718: 		    $score = 'excused';
1.125     ng       3719: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 3720: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       3721: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   3722: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   3723: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   3724: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 3725: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3726: 		    $changeflag++;
                   3727: 		    $newpts = '';
1.269     raeburn  3728:                     
                   3729:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   3730:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   3731:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   3732:                     if ($aggtries > 0) {
                   3733:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3734:                         $aggregateflag = 1;
                   3735:                     }
1.71      ng       3736: 		}
1.207     albertel 3737: 		my $display_part=&get_display_part($partid,undef,
                   3738: 						   $curRes->symb());
1.257     albertel 3739: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 3740: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       3741: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
                   3742: 		    '&nbsp;<br>';
1.207     albertel 3743: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       3744: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.71      ng       3745: 		    '&nbsp;<br>';
                   3746: 
                   3747: 		$question++;
1.125     ng       3748: 		next if ($dropMenu eq 'reset status' || ($newpts == $oldpts && $score ne 'excused'));
                   3749: 
1.71      ng       3750: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       3751: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 3752: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       3753: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       3754: 
                   3755: 		$changeflag++;
                   3756: 	    }
                   3757: 	    if (scalar(keys(%newrecord)) > 0) {
1.257     albertel 3758: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       3759: 					$udom,$uname);
                   3760: 	    }
1.269     raeburn  3761:             if ($aggregateflag) {
                   3762:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   3763:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   3764:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   3765:             }
1.125     ng       3766: 
1.71      ng       3767: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   3768: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   3769: 		'</tr>';
1.68      ng       3770: 
1.196     albertel 3771: 	    $prob++;
1.68      ng       3772: 	}
1.71      ng       3773:         $curRes = $iterator->next();
1.68      ng       3774:     }
1.98      albertel 3775: 
1.71      ng       3776:     $studentTable.='</td></tr></table></td></tr></table>';
1.257     albertel 3777:     $studentTable.=&show_grading_menu_form($env{'form.symb'},$env{'form.url'});
1.76      ng       3778:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   3779: 		  'The scores were changed for '.
                   3780: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   3781:     $request->print($grademsg.$studentTable);
1.68      ng       3782: 
1.70      ng       3783:     return '';
                   3784: }
                   3785: 
1.72      ng       3786: #-------- end of section for handling grading by page/sequence ---------
                   3787: #
                   3788: #-------------------------------------------------------------------
                   3789: 
1.75      albertel 3790: #--------------------Scantron Grading-----------------------------------
                   3791: #
                   3792: #------ start of section for handling grading by page/sequence ---------
                   3793: 
1.81      albertel 3794: sub defaultFormData {
                   3795:     my ($symb,$url)=@_;
                   3796:     return '
                   3797:       <input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
                   3798:      '<input type="hidden" name="url"     value="'.$url.'" />'."\n".
1.257     albertel 3799:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   3800:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 3801: }
                   3802: 
1.75      albertel 3803: sub getSequenceDropDown {
                   3804:     my ($request,$symb)=@_;
                   3805:     my $result='<select name="selectpage">'."\n";
                   3806:     my ($titles,$symbx) = &getSymbMap($request);
1.137     albertel 3807:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 3808:     my $ctr=0;
                   3809:     foreach (@$titles) {
                   3810: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3811: 	$result.='<option value="'.$$symbx{$_}.'" '.
                   3812: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="on"' : '').
                   3813: 	    '>'.$showtitle.'</option>'."\n";
                   3814: 	$ctr++;
                   3815:     }
                   3816:     $result.= '</select>';
                   3817:     return $result;
                   3818: }
                   3819: 
1.202     albertel 3820: sub scantron_filenames {
1.257     albertel 3821:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3822:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 3823:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.162     albertel 3824: 				    &Apache::loncommon::propath($cdom,$cname));
1.202     albertel 3825:     my @possiblenames;
1.201     albertel 3826:     foreach my $filename (sort(@files)) {
1.157     albertel 3827: 	($filename)=split(/&/,$filename);
                   3828: 	if ($filename!~/^scantron_orig_/) { next ; }
                   3829: 	$filename=~s/^scantron_orig_//;
1.202     albertel 3830: 	push(@possiblenames,$filename);
                   3831:     }
                   3832:     return @possiblenames;
                   3833: }
                   3834: 
                   3835: sub scantron_uploads {
1.209     ng       3836:     my ($file2grade) = @_;
1.202     albertel 3837:     my $result=	'<select name="scantron_selectfile">';
                   3838:     $result.="<option></option>";
                   3839:     foreach my $filename (sort(&scantron_filenames())) {
1.209     ng       3840: 	$result.="<option".($filename eq $file2grade ? ' selected="on"':'').">$filename</option>\n";
1.81      albertel 3841:     }
                   3842:     $result.="</select>";
                   3843:     return $result;
                   3844: }
                   3845: 
1.82      albertel 3846: sub scantron_scantab {
                   3847:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   3848:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 3849:     $result.='<option></option>'."\n";
1.82      albertel 3850:     foreach my $line (<$fh>) {
                   3851: 	my ($name,$descrip)=split(/:/,$line);
                   3852: 	if ($name =~ /^\#/) { next; }
                   3853: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   3854:     }
                   3855:     $result.='</select>'."\n";
                   3856: 
                   3857:     return $result;
                   3858: }
                   3859: 
1.186     albertel 3860: sub scantron_CODElist {
1.257     albertel 3861:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3862:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 3863:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   3864:     my $namechoice='<option></option>';
1.225     albertel 3865:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 3866: 	if ($name =~ /^error: 2 /) { next; }
1.186     albertel 3867: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   3868:     }
                   3869:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   3870:     return $namechoice;
                   3871: }
                   3872: 
                   3873: sub scantron_CODEunique {
                   3874:     my $result='<nobr>
1.272     albertel 3875:                  <label><input type="radio" name="scantron_CODEunique"
                   3876:                         value="Yes" checked="on" /> Yes </label>
1.186     albertel 3877:                 </nobr>
                   3878:                 <nobr>
1.272     albertel 3879:                  <label><input type="radio" name="scantron_CODEunique"
                   3880:                         value="No" /> No </label>
1.186     albertel 3881:                 </nobr>';
                   3882:     return $result;
                   3883: }
                   3884: 
1.75      albertel 3885: sub scantron_selectphase {
1.209     ng       3886:     my ($r,$file2grade) = @_;
1.75      albertel 3887:     my ($symb,$url)=&get_symb_and_url($r);
                   3888:     if (!$symb) {return '';}
                   3889:     my $sequence_selector=&getSequenceDropDown($r,$symb);
1.81      albertel 3890:     my $default_form_data=&defaultFormData($symb,$url);
                   3891:     my $grading_menu_button=&show_grading_menu_form($symb,$url);
1.209     ng       3892:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 3893:     my $format_selector=&scantron_scantab();
1.186     albertel 3894:     my $CODE_selector=&scantron_CODElist();
                   3895:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 3896:     my $result;
1.157     albertel 3897:     #FIXME allow instructor to be able to download the scantron file
                   3898:     # and to upload it,
1.75      albertel 3899:     $result.= <<SCANTRONFORM;
1.162     albertel 3900:     <table width="100%" border="0">
1.75      albertel 3901:     <tr>
1.226     albertel 3902:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 3903:       <td bgcolor="#777777">
1.203     albertel 3904:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 3905:         $default_form_data
1.75      albertel 3906:         <table width="100%" border="0">
                   3907:           <tr bgcolor="#e6ffff">
1.174     albertel 3908:             <td colspan="2">
                   3909:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 3910:             </td>
                   3911:           </tr>
                   3912:           <tr bgcolor="#ffffe6">
1.174     albertel 3913:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 3914:           </tr>
                   3915:           <tr bgcolor="#ffffe6">
1.174     albertel 3916:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 3917:           </tr>
1.82      albertel 3918:           <tr bgcolor="#ffffe6">
1.174     albertel 3919:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 3920:           </tr>
1.157     albertel 3921:           <tr bgcolor="#ffffe6">
1.186     albertel 3922:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   3923:           </tr>
                   3924:           <tr bgcolor="#ffffe6">
                   3925:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   3926:           </tr>
                   3927:           <tr bgcolor="#ffffe6">
1.187     albertel 3928: 	    <td> Options: </td>
                   3929:             <td>
1.272     albertel 3930: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
                   3931:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all exisiting corrections</label>
1.187     albertel 3932: 	    </td>
                   3933:           </tr>
                   3934:           <tr bgcolor="#ffffe6">
1.174     albertel 3935:             <td colspan="2">
1.265     www      3936:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 3937:             </td>
                   3938:           </tr>
                   3939:         </table>
1.226     albertel 3940:        </td>
                   3941:      </form>
1.162     albertel 3942:     </tr>
                   3943: SCANTRONFORM
                   3944:    
                   3945:     $r->print($result);
                   3946: 
1.257     albertel 3947:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   3948:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 3949: 
                   3950:         $r->print(<<SCANTRONFORM);
                   3951:     <tr>
                   3952:       <td bgcolor="#777777">
                   3953:         <table width="100%" border="0">
                   3954:           <tr bgcolor="#e6ffff">
                   3955:             <td>
1.174     albertel 3956:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 3957:             </td>
                   3958:           </tr>
                   3959:           <tr bgcolor="#ffffe6">
                   3960:             <td>
                   3961: SCANTRONFORM
1.174     albertel 3962:     my $default_form_data=&defaultFormData(&get_symb_and_url($r,1));
1.257     albertel 3963:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3964:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 3965:     $r->print(<<UPLOAD);
                   3966:               <script type="text/javascript" language="javascript">
                   3967:     function checkUpload(formname) {
                   3968: 	if (formname.upfile.value == "") {
                   3969: 	    alert("Please use the browse button to select a file from your local directory.");
                   3970: 	    return false;
                   3971: 	}
                   3972: 	formname.submit();
                   3973:     }
                   3974:               </script>
                   3975: 
                   3976:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   3977:                 $default_form_data
                   3978:                 <input name='courseid' type='hidden' value='$cnum' />
                   3979:                 <input name='domainid' type='hidden' value='$cdom' />
                   3980:                 <input name='command' value='scantronupload_save' type='hidden' />
                   3981:                 File to upload:<input type="file" name="upfile" size="50" />
                   3982:                 <br />
                   3983:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   3984:               </form>
                   3985: UPLOAD
1.162     albertel 3986: 
                   3987:         $r->print(<<SCANTRONFORM);
                   3988:             </td>
                   3989:           </tr>
1.75      albertel 3990:         </table>
                   3991:       </td>
                   3992:     </tr>
1.162     albertel 3993: SCANTRONFORM
                   3994:     }
1.187     albertel 3995:     $r->print(<<SCANTRONFORM);
                   3996:     <tr>
1.226     albertel 3997:       <form action='/adm/grades' name='scantron_download'>
                   3998:         <td bgcolor="#777777">
1.187     albertel 3999:           <input type="hidden" name="command" value="scantron_download" />
                   4000:           <table width="100%" border="0">
                   4001:             <tr bgcolor="#e6ffff">
                   4002:               <td colspan="2">
                   4003:                 &nbsp;<b>Download a scoring office file</b>
                   4004:               </td>
                   4005:             </tr>
                   4006:             <tr bgcolor="#ffffe6">
                   4007:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4008:             </tr>
                   4009:             <tr bgcolor="#ffffe6">
                   4010:               <td colspan="2">
1.202     albertel 4011:                 <input type="submit" value="Show List of Files" />
1.187     albertel 4012:               </td>
                   4013:             </tr>
                   4014:           </table>
1.226     albertel 4015:         </td>
                   4016:       </form>
1.187     albertel 4017:     </tr>
                   4018: SCANTRONFORM
1.162     albertel 4019: 
                   4020:     $r->print(<<SCANTRONFORM);
1.75      albertel 4021:   </table>
1.81      albertel 4022: $grading_menu_button
1.75      albertel 4023: SCANTRONFORM
                   4024: 
1.162     albertel 4025:     return
1.75      albertel 4026: }
                   4027: 
1.82      albertel 4028: sub get_scantron_config {
                   4029:     my ($which) = @_;
                   4030:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4031:     my %config;
1.157     albertel 4032:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4033:     foreach my $line (<$fh>) {
                   4034: 	my ($name,$descrip)=split(/:/,$line);
                   4035: 	if ($name ne $which ) { next; }
                   4036: 	chomp($line);
                   4037: 	my @config=split(/:/,$line);
                   4038: 	$config{'name'}=$config[0];
                   4039: 	$config{'description'}=$config[1];
                   4040: 	$config{'CODElocation'}=$config[2];
                   4041: 	$config{'CODEstart'}=$config[3];
                   4042: 	$config{'CODElength'}=$config[4];
                   4043: 	$config{'IDstart'}=$config[5];
                   4044: 	$config{'IDlength'}=$config[6];
                   4045: 	$config{'Qstart'}=$config[7];
                   4046: 	$config{'Qlength'}=$config[8];
                   4047: 	$config{'Qoff'}=$config[9];
                   4048: 	$config{'Qon'}=$config[10];
1.157     albertel 4049: 	$config{'PaperID'}=$config[11];
                   4050: 	$config{'PaperIDlength'}=$config[12];
                   4051: 	$config{'FirstName'}=$config[13];
                   4052: 	$config{'FirstNamelength'}=$config[14];
                   4053: 	$config{'LastName'}=$config[15];
                   4054: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4055: 	last;
                   4056:     }
                   4057:     return %config;
                   4058: }
                   4059: 
                   4060: sub username_to_idmap {
                   4061:     my ($classlist)= @_;
                   4062:     my %idmap;
                   4063:     foreach my $student (keys(%$classlist)) {
                   4064: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4065: 	    $student;
                   4066:     }
                   4067:     return %idmap;
                   4068: }
                   4069: 
1.157     albertel 4070: sub scantron_fixup_scanline {
                   4071:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   4072:     if ($field eq 'ID') {
                   4073: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 4074: 	    return ($line,1,'New value too large');
1.157     albertel 4075: 	}
                   4076: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   4077: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   4078: 				     $args->{'newid'});
                   4079: 	}
                   4080: 	substr($line,$$scantron_config{'IDstart'}-1,
                   4081: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   4082: 	if ($args->{'newid'}=~/^\s*$/) {
                   4083: 	    &scan_data($scan_data,"$whichline.user",
                   4084: 		       $args->{'username'}.':'.$args->{'domain'});
                   4085: 	}
1.186     albertel 4086:     } elsif ($field eq 'CODE') {
1.192     albertel 4087: 	if ($args->{'CODE_ignore_dup'}) {
                   4088: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   4089: 	}
                   4090: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   4091: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 4092: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   4093: 		return ($line,1,'New CODE value too large');
                   4094: 	    }
                   4095: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   4096: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   4097: 	    }
                   4098: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   4099: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 4100: 	}
1.157     albertel 4101:     } elsif ($field eq 'answer') {
                   4102: 	my $length=$scantron_config->{'Qlength'};
                   4103: 	my $off=$scantron_config->{'Qoff'};
                   4104: 	my $on=$scantron_config->{'Qon'};
                   4105: 	my $answer=${off}x$length;
                   4106: 	if ($args->{'response'} eq 'none') {
                   4107: 	    &scan_data($scan_data,
                   4108: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   4109: 	} else {
1.274     albertel 4110: 	    if ($on eq 'letter') {
                   4111: 		my @alphabet=('A'..'Z');
                   4112: 		$answer=$alphabet[$args->{'response'}];
                   4113: 	    } elsif ($on eq 'number') {
                   4114: 		$answer=$args->{'response'}+1;
                   4115: 	    } else {
                   4116: 		substr($answer,$args->{'response'},1)=$on;
                   4117: 	    }
1.157     albertel 4118: 	    &scan_data($scan_data,
                   4119: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   4120: 	}
                   4121: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   4122: 	substr($line,$where-1,$length)=$answer;
                   4123:     }
                   4124:     return $line;
                   4125: }
                   4126: 
                   4127: sub scan_data {
                   4128:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 4129:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 4130:     if (defined($value)) {
                   4131: 	$scan_data->{$filename.'_'.$key} = $value;
                   4132:     }
                   4133:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   4134:     return $scan_data->{$filename.'_'.$key};
                   4135: }
                   4136: 
1.82      albertel 4137: sub scantron_parse_scanline {
1.194     albertel 4138:     my ($line,$whichline,$scantron_config,$scan_data,$justHeader)=@_;
1.82      albertel 4139:     my %record;
                   4140:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);
                   4141:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);
                   4142:     if ($$scantron_config{'CODElocation'} ne 0) {
                   4143: 	if ($$scantron_config{'CODElocation'} < 0) {
1.191     albertel 4144: 	    $record{'scantron.CODE'}=substr($data,
                   4145: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 4146: 					    $$scantron_config{'CODElength'});
1.191     albertel 4147: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   4148: 		$record{'scantron.useCODE'}=1;
                   4149: 	    }
1.192     albertel 4150: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   4151: 		$record{'scantron.CODE_ignore_dup'}=1;
                   4152: 	    }
1.82      albertel 4153: 	} else {
                   4154: 	    #FIXME interpret first N questions
                   4155: 	}
                   4156:     }
1.83      albertel 4157:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   4158: 				  $$scantron_config{'IDlength'});
1.157     albertel 4159:     $record{'scantron.PaperID'}=
                   4160: 	substr($data,$$scantron_config{'PaperID'}-1,
                   4161: 	       $$scantron_config{'PaperIDlength'});
                   4162:     $record{'scantron.FirstName'}=
                   4163: 	substr($data,$$scantron_config{'FirstName'}-1,
                   4164: 	       $$scantron_config{'FirstNamelength'});
                   4165:     $record{'scantron.LastName'}=
                   4166: 	substr($data,$$scantron_config{'LastName'}-1,
                   4167: 	       $$scantron_config{'LastNamelength'});
1.194     albertel 4168:     if ($justHeader) { return \%record; }
                   4169: 
1.82      albertel 4170:     my @alphabet=('A'..'Z');
                   4171:     my $questnum=0;
                   4172:     while ($questions) {
                   4173: 	$questnum++;
                   4174: 	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
                   4175: 	substr($questions,0,$$scantron_config{'Qlength'})='';
1.83      albertel 4176: 	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
1.239     albertel 4177: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.274     albertel 4178: 	    if ($currentquest eq '?') {
                   4179: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4180: 		$record{"scantron.$questnum.answer"}='';
                   4181: 	    } elsif (!$currentquest 
                   4182: 		     || $currentquest eq $$scantron_config{'Qoff'}
                   4183: 		     || $currentquest !~ /^[A-Z]$/) {
1.239     albertel 4184: 		$record{"scantron.$questnum.answer"}='';
                   4185: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4186: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4187: 		}
                   4188: 	    } else {
                   4189: 		$record{"scantron.$questnum.answer"}=$currentquest;
                   4190: 	    }
                   4191: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.274     albertel 4192: 	    if ($currentquest eq '?') {
                   4193: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4194: 		$record{"scantron.$questnum.answer"}='';
                   4195: 		} elsif (!$currentquest 
                   4196: 			 || $currentquest eq $$scantron_config{'Qoff'} 
                   4197: 			 || $currentquest !~ /^\d$/) {
1.239     albertel 4198: 		$record{"scantron.$questnum.answer"}='';
                   4199: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4200: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4201: 		}
                   4202: 	    } else {
                   4203: 		$record{"scantron.$questnum.answer"}=
                   4204: 		    $alphabet[$currentquest-1];
                   4205: 	    }
1.82      albertel 4206: 	} else {
1.239     albertel 4207: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
                   4208: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}) {
                   4209: 		$record{"scantron.$questnum.answer"}='';
                   4210: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4211: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4212: 		}
                   4213: 	    } else {
                   4214: 		$record{"scantron.$questnum.answer"}=
                   4215: 		    $alphabet[length($array[0])];
                   4216: 	    }
                   4217: 	    if (scalar(@array) gt 2) {
                   4218: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4219: 		my @ans=@array;
                   4220: 		my $i=length($ans[0]);shift(@ans);
                   4221: 		while ($#ans) {
                   4222: 		    $i+=length($ans[0])+1;
                   4223: 		    $record{"scantron.$questnum.answer"}.=$alphabet[$i];
                   4224: 		    shift(@ans);
                   4225: 		}
                   4226: 	    }
1.82      albertel 4227: 	}
                   4228:     }
1.83      albertel 4229:     $record{'scantron.maxquest'}=$questnum;
                   4230:     return \%record;
1.82      albertel 4231: }
                   4232: 
                   4233: sub scantron_add_delay {
1.140     albertel 4234:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   4235:     push(@$delayqueue,
                   4236: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   4237: 	  'ecode' => $errorcode }
                   4238: 	 );
1.82      albertel 4239: }
                   4240: 
                   4241: sub scantron_find_student {
1.157     albertel 4242:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 4243:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 4244:     if ($scanID =~ /^\s*$/) {
                   4245:  	return &scan_data($scan_data,"$line.user");
                   4246:     }
1.83      albertel 4247:     foreach my $id (keys(%$idmap)) {
1.157     albertel 4248:  	if (lc($id) eq lc($scanID)) {
                   4249:  	    return $$idmap{$id};
                   4250:  	}
1.83      albertel 4251:     }
                   4252:     return undef;
                   4253: }
                   4254: 
                   4255: sub scantron_filter {
                   4256:     my ($curres)=@_;
1.215     albertel 4257:                         # randomout is dysfunctional at best for this purpose
                   4258:     if (ref($curres) && $curres->is_problem()) { #&& !$curres->randomout) {
1.83      albertel 4259: 	return 1;
                   4260:     }
                   4261:     return 0;
1.82      albertel 4262: }
                   4263: 
1.157     albertel 4264: sub scantron_process_corrections {
                   4265:     my ($r) = @_;
1.257     albertel 4266:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 4267:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4268:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 4269:     my $which=$env{'form.scantron_line'};
1.200     albertel 4270:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 4271:     my ($skip,$err,$errmsg);
1.257     albertel 4272:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 4273: 	$skip=1;
1.257     albertel 4274:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   4275: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   4276: 	    $env{'form.scantron_domain'};
1.157     albertel 4277: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   4278: 	($line,$err,$errmsg)=
                   4279: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   4280: 				     'ID',{'newid'=>$newid,
1.257     albertel 4281: 				    'username'=>$env{'form.scantron_username'},
                   4282: 				    'domain'=>$env{'form.scantron_domain'}});
                   4283:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   4284: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 4285: 	my $newCODE;
1.192     albertel 4286: 	my %args;
1.190     albertel 4287: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 4288: 	    $newCODE='use_unfound';
1.190     albertel 4289: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 4290: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 4291: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 4292: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 4293: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 4294: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 4295: 	}
1.257     albertel 4296: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 4297: 	    $args{'CODE_ignore_dup'}=1;
                   4298: 	}
                   4299: 	$args{'CODE'}=$newCODE;
1.186     albertel 4300: 	($line,$err,$errmsg)=
                   4301: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 4302: 				     'CODE',\%args);
1.257     albertel 4303:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   4304: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 4305: 	    ($line,$err,$errmsg)=
                   4306: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   4307: 					 $which,'answer',
                   4308: 					 { 'question'=>$question,
1.257     albertel 4309: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 4310: 	    if ($err) { last; }
                   4311: 	}
                   4312:     }
                   4313:     if ($err) {
                   4314: 	$r->print("Unable to accept last correction, an error occurred :$errmsg:");
                   4315:     } else {
1.200     albertel 4316: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 4317: 	&scantron_putfile($scanlines,$scan_data);
                   4318:     }
                   4319: }
                   4320: 
1.200     albertel 4321: sub reset_skipping_status {
                   4322:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4323:     &scan_data($scan_data,'remember_skipping',undef,1);
                   4324:     &scantron_putfile(undef,$scan_data);
                   4325: }
                   4326: 
                   4327: sub allow_skipping {
                   4328:     my ($scan_data,$i)=@_;
                   4329:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
                   4330:     delete($remembered{$i});
                   4331:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   4332: }
                   4333: 
                   4334: sub should_be_skipped {
                   4335:     my ($scan_data,$i)=@_;
1.257     albertel 4336:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 4337: 	# not redoing old skips
                   4338: 	return 0;
                   4339:     }
                   4340:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
                   4341:     if (exists($remembered{$i})) { return 0; }
                   4342:     return 1;
                   4343: }
                   4344: 
                   4345: sub remember_current_skipped {
                   4346:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4347:     my %to_remember;
                   4348:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   4349: 	if ($scanlines->{'skipped'}[$i]) {
                   4350: 	    $to_remember{$i}=1;
                   4351: 	}
                   4352:     }
                   4353:     &Apache::lonnet::logthis('remembering '.join(':',%to_remember));
                   4354:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   4355:     &scantron_putfile(undef,$scan_data);
                   4356: }
                   4357: 
                   4358: sub check_for_error {
                   4359:     my ($r,$result)=@_;
                   4360:     if ($result ne 'ok' && $result ne 'not_found' ) {
                   4361: 	$r->print("An error occured ($result) when trying to Remove the existing corrections.");
                   4362:     }
                   4363: }
1.157     albertel 4364: 
1.203     albertel 4365: sub scantron_warning_screen {
                   4366:     my ($button_text)=@_;
1.257     albertel 4367:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.203     albertel 4368:     return (<<STUFF);
                   4369: <p>
                   4370: <font color="red">Please double check the information
                   4371:                  below before clicking on '$button_text'</font>
                   4372: </p>
                   4373: <table>
                   4374: <tr><td><b>Sequence To be Graded:</b></td><td>$title</td></tr>
1.257     albertel 4375: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.203     albertel 4376: </table>
                   4377: </font>
                   4378: <br />
                   4379: <p> If this information is correct, please click on '$button_text'.</p>
                   4380: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   4381: 
                   4382: <br />
                   4383: STUFF
                   4384: }
                   4385: 
                   4386: sub scantron_do_warning {
                   4387:     my ($r)=@_;
                   4388:     my ($symb,$url)=&get_symb_and_url($r);
                   4389:     if (!$symb) {return '';}
                   4390:     my $default_form_data=&defaultFormData($symb,$url);
                   4391:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 4392:     if ( $env{'form.selectpage'} eq '' ||
                   4393: 	 $env{'form.scantron_selectfile'} eq '' ||
                   4394: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 4395: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 4396: 	if ( $env{'form.selectpage'} eq '') {
1.237     albertel 4397: 	    $r->print('<p><font color="red">You have not selected a Sequence to grade</font></p>');
                   4398: 	} 
1.257     albertel 4399: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.237     albertel 4400: 	    $r->print('<p><font color="red">You have not selected a file that contains the student\'s response data.</font></p>');
                   4401: 	} 
1.257     albertel 4402: 	if ( $env{'form.scantron_format'} eq '') {
1.237     albertel 4403: 	    $r->print('<p><font color="red">You have not selected a the format of the student\'s response data.</font></p>');
                   4404: 	} 
                   4405:     } else {
1.265     www      4406: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 4407: 	$r->print(<<STUFF);
1.203     albertel 4408: $warning
1.265     www      4409: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 4410: <input type="hidden" name="command" value="scantron_validate" />
                   4411: STUFF
1.237     albertel 4412:     }
                   4413:     $r->print("</form><br />".&show_grading_menu_form($symb,$url)."</body></html>");
1.203     albertel 4414:     return '';
                   4415: }
                   4416: 
                   4417: sub scantron_form_start {
                   4418:     my ($max_bubble)=@_;
                   4419:     my $result= <<SCANTRONFORM;
                   4420: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 4421:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   4422:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   4423:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 4424:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 4425:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   4426:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   4427:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   4428:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.203     albertel 4429: SCANTRONFORM
                   4430:     return $result;
                   4431: }
                   4432: 
1.157     albertel 4433: sub scantron_validate_file {
                   4434:     my ($r) = @_;
                   4435:     my ($symb,$url)=&get_symb_and_url($r);
                   4436:     if (!$symb) {return '';}
                   4437:     my $default_form_data=&defaultFormData($symb,$url);
1.200     albertel 4438:     
                   4439:     # do the detection of only doing skipped records first befroe we delete
                   4440:     # them  when doing the corrections reset
1.257     albertel 4441:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 4442: 	&reset_skipping_status();
                   4443:     }
1.257     albertel 4444:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 4445: 	&remember_current_skipped();
                   4446: 	&scantron_remove_file('skipped');
1.257     albertel 4447: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 4448:     }
                   4449: 
1.257     albertel 4450:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 4451: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   4452: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   4453: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 4454: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 4455:     }
1.200     albertel 4456: 
1.257     albertel 4457:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 4458: 	&scantron_process_corrections($r);
                   4459:     }
1.191     albertel 4460:     $r->print("<p>Gathering neccessary info.</p>");$r->rflush();
1.157     albertel 4461:     #get the student pick code ready
                   4462:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.203     albertel 4463:     my $max_bubble=&scantron_get_maxbubble($r);
                   4464:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 4465:     $r->print($result);
                   4466:     
                   4467:     my @validate_phases=( 'ID',
                   4468: 			  'CODE',
                   4469: 			  'doublebubble',
                   4470: 			  'missingbubbles');
1.257     albertel 4471:     if (!$env{'form.validatepass'}) {
                   4472: 	$env{'form.validatepass'} = 0;
1.157     albertel 4473:     }
1.257     albertel 4474:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 4475: 
                   4476:     my $stop=0;
                   4477:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   4478: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   4479: 	$r->rflush();
                   4480: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   4481: 	{
                   4482: 	    no strict 'refs';
                   4483: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   4484: 	}
                   4485:     }
                   4486:     if (!$stop) {
1.203     albertel 4487: 	my $warning=&scantron_warning_screen('Start Grading');
                   4488: 	$r->print(<<STUFF);
                   4489: Validation process complete.<br />
                   4490: $warning
                   4491: <input type="submit" name="submit" value="Start Grading" />
                   4492: <input type="hidden" name="command" value="scantron_process" />
                   4493: STUFF
                   4494: 
1.157     albertel 4495:     } else {
                   4496: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   4497: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   4498:     }
                   4499:     if ($stop) {
                   4500: 	$r->print('<input type="submit" name="submit" value="Continue ->" />');
                   4501: 	$r->print(' using corrected info <br />');
                   4502: 	$r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   4503: 	$r->print(" this scanline saving it for later.");
                   4504:     }
                   4505:     $r->print(" </form><br />".&show_grading_menu_form($symb,$url).
                   4506: 	      "</body></html>");
                   4507:     return '';
                   4508: }
                   4509: 
1.200     albertel 4510: sub scantron_remove_file {
1.192     albertel 4511:     my ($which)=@_;
1.257     albertel 4512:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4513:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 4514:     my $file='scantron_';
1.200     albertel 4515:     if ($which eq 'corrected' || $which eq 'skipped') {
                   4516: 	$file.=$which.'_';
1.192     albertel 4517:     } else {
                   4518: 	return 'refused';
                   4519:     }
1.257     albertel 4520:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 4521:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   4522: }
                   4523: 
                   4524: sub scantron_remove_scan_data {
1.257     albertel 4525:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4526:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 4527:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   4528:     my @todelete;
1.257     albertel 4529:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 4530:     foreach my $key (@keys) {
                   4531: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 4532: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 4533: 		$key=~/remember_skipping/) {
                   4534: 		next;
                   4535: 	    }
1.192     albertel 4536: 	    push(@todelete,$key);
                   4537: 	}
                   4538:     }
1.200     albertel 4539:     my $result;
1.192     albertel 4540:     if (@todelete) {
1.200     albertel 4541: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 4542:     }
                   4543:     return $result;
                   4544: }
                   4545: 
1.157     albertel 4546: sub scantron_getfile {
1.200     albertel 4547:     #FIXME really would prefer a scantron directory
1.257     albertel 4548:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4549:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 4550:     my $lines;
                   4551:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 4552: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 4553:     my %scanlines;
                   4554:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   4555:     my $temp=$scanlines{'orig'};
                   4556:     $scanlines{'count'}=$#$temp;
                   4557: 
                   4558:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 4559: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 4560:     if ($lines eq '-1') {
                   4561: 	$scanlines{'corrected'}=[];
                   4562:     } else {
                   4563: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   4564:     }
                   4565:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 4566: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 4567:     if ($lines eq '-1') {
                   4568: 	$scanlines{'skipped'}=[];
                   4569:     } else {
                   4570: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   4571:     }
1.175     albertel 4572:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 4573:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   4574:     my %scan_data = @tmp;
                   4575:     return (\%scanlines,\%scan_data);
                   4576: }
                   4577: 
                   4578: sub lonnet_putfile {
                   4579:     my ($contents,$filename)=@_;
1.257     albertel 4580:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4581:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4582:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275   ! albertel 4583:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 4584: 
                   4585: }
                   4586: 
                   4587: sub scantron_putfile {
                   4588:     my ($scanlines,$scan_data) = @_;
1.200     albertel 4589:     #FIXME really would prefer a scantron directory
1.257     albertel 4590:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4591:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 4592:     if ($scanlines) {
                   4593: 	my $prefix='scantron_';
1.157     albertel 4594: # no need to update orig, shouldn't change
                   4595: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 4596: #		    $env{'form.scantron_selectfile'});
1.200     albertel 4597: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   4598: 			$prefix.'corrected_'.
1.257     albertel 4599: 			$env{'form.scantron_selectfile'});
1.200     albertel 4600: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   4601: 			$prefix.'skipped_'.
1.257     albertel 4602: 			$env{'form.scantron_selectfile'});
1.200     albertel 4603:     }
1.175     albertel 4604:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 4605: }
                   4606: 
                   4607: sub scantron_get_line {
1.200     albertel 4608:     my ($scanlines,$scan_data,$i)=@_;
                   4609:     if (&should_be_skipped($scan_data,$i)) { return undef; }
                   4610:     if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 4611:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   4612:     return $scanlines->{'orig'}[$i]; 
                   4613: }
                   4614: 
1.200     albertel 4615: sub get_todo_count {
                   4616:     my ($scanlines,$scan_data)=@_;
                   4617:     my $count=0;
                   4618:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   4619: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   4620: 	if ($line=~/^[\s\cz]*$/) { next; }
                   4621: 	$count++;
                   4622:     }
                   4623:     return $count;
                   4624: }
                   4625: 
1.157     albertel 4626: sub scantron_put_line {
1.200     albertel 4627:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 4628:     if ($skip) {
                   4629: 	$scanlines->{'skipped'}[$i]=$newline;
1.200     albertel 4630: 	&allow_skipping($scan_data,$i);
1.157     albertel 4631: 	return;
                   4632:     }
                   4633:     $scanlines->{'corrected'}[$i]=$newline;
                   4634: }
                   4635: 
                   4636: sub scantron_validate_ID {
                   4637:     my ($r,$currentphase) = @_;
                   4638:     
                   4639:     #get student info
                   4640:     my $classlist=&Apache::loncoursedata::get_classlist();
                   4641:     my %idmap=&username_to_idmap($classlist);
                   4642: 
                   4643:     #get scantron line setup
1.257     albertel 4644:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 4645:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4646: 
                   4647:     my %found=('ids'=>{},'usernames'=>{});
                   4648:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 4649: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 4650: 	if ($line=~/^[\s\cz]*$/) { next; }
                   4651: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   4652: 						 $scan_data);
                   4653: 	my $id=$$scan_record{'scantron.ID'};
                   4654: 	my $found;
                   4655: 	foreach my $checkid (keys(%idmap)) {
                   4656: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   4657: 	}
                   4658: 	if ($found) {
                   4659: 	    my $username=$idmap{$found};
                   4660: 	    if ($found{'ids'}{$found}) {
                   4661: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   4662: 					 $line,'duplicateID',$found);
1.194     albertel 4663: 		return(1,$currentphase);
1.157     albertel 4664: 	    } elsif ($found{'usernames'}{$username}) {
                   4665: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   4666: 					 $line,'duplicateID',$username);
1.194     albertel 4667: 		return(1,$currentphase);
1.157     albertel 4668: 	    }
1.186     albertel 4669: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 4670: 	    $found{'ids'}{$found}++;
                   4671: 	    $found{'usernames'}{$username}++;
                   4672: 	} else {
                   4673: 	    if ($id =~ /^\s*$/) {
1.158     albertel 4674: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 4675: 		if (defined($username) && $found{'usernames'}{$username}) {
                   4676: 		    &scantron_get_correction($r,$i,$scan_record,
                   4677: 					     \%scantron_config,
                   4678: 					     $line,'duplicateID',$username);
1.194     albertel 4679: 		    return(1,$currentphase);
1.157     albertel 4680: 		} elsif (!defined($username)) {
                   4681: 		    &scantron_get_correction($r,$i,$scan_record,
                   4682: 					     \%scantron_config,
                   4683: 					     $line,'incorrectID');
1.194     albertel 4684: 		    return(1,$currentphase);
1.157     albertel 4685: 		}
                   4686: 		$found{'usernames'}{$username}++;
                   4687: 	    } else {
                   4688: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   4689: 					 $line,'incorrectID');
1.194     albertel 4690: 		return(1,$currentphase);
1.157     albertel 4691: 	    }
                   4692: 	}
                   4693:     }
                   4694: 
                   4695:     return (0,$currentphase+1);
                   4696: }
                   4697: 
                   4698: sub scantron_get_correction {
                   4699:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   4700: 
                   4701: #FIXME in the case of a duplicated ID the previous line, probaly need
                   4702: #to show both the current line and the previous one and allow skipping
                   4703: #the previous one or the current one
                   4704: 
1.161     albertel 4705:     $r->print("<p><b>An error was detected ($error)</b>");
1.157     albertel 4706:     if ( defined($$scan_record{'scantron.PaperID'}) ) {
                   4707: 	$r->print(" for PaperID <tt>".
                   4708: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   4709:     } else {
                   4710: 	$r->print(" in scanline $i <pre>".
                   4711: 		  $line."</pre> \n");
                   4712:     }
1.242     albertel 4713:     my $message="<p>The ID on the form is  <tt>".
                   4714: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   4715: 	"The name on the paper is ".
                   4716: 	$$scan_record{'scantron.LastName'}.",".
                   4717: 	$$scan_record{'scantron.FirstName'}."</p>";
                   4718: 
1.157     albertel 4719:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   4720:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   4721:     if ($error =~ /ID$/) {
1.186     albertel 4722: 	if ($error eq 'incorrectID') {
1.157     albertel 4723: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   4724: 	} elsif ($error eq 'duplicateID') {
                   4725: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   4726: 	}
1.242     albertel 4727: 	$r->print($message);
1.157     albertel 4728: 	$r->print("<p>How should I handle this? <br /> \n");
                   4729: 	$r->print("\n<ul><li> ");
                   4730: 	#FIXME it would be nice if this sent back the user ID and
                   4731: 	#could do partial userID matches
                   4732: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   4733: 				       'scantron_username','scantron_domain'));
                   4734: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   4735: 	$r->print("\n@".
1.257     albertel 4736: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 4737: 
                   4738: 	$r->print('</li>');
1.186     albertel 4739:     } elsif ($error =~ /CODE$/) {
                   4740: 	if ($error eq 'incorrectCODE') {
1.187     albertel 4741: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 4742: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 4743: 	    $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 4744: 	}
1.224     albertel 4745: 	$r->print("<p>The CODE on the form is  <tt>'".
                   4746: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 4747: 	$r->print($message);
1.186     albertel 4748: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 4749: 	$r->print("\n<br /> ");
1.194     albertel 4750: 	my $i=0;
1.273     albertel 4751: 	if ($error eq 'incorrectCODE' 
                   4752: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 4753: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
                   4754: 	    foreach my $testcode (@{$closest}) {
                   4755: 		my $checked='';
                   4756: 		if (!$i) { $checked=' checked="on" '; }
1.272     albertel 4757: 		$r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked /> Use the similar CODE <b><tt>".$testcode."</tt></b> instead.</label><input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.194     albertel 4758: 		$r->print("\n<br />");
                   4759: 		$i++;
                   4760: 	    }
                   4761: 	}
1.273     albertel 4762: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
                   4763: 	    my $checked; if (!$i) { $checked=' checked="on" '; }
                   4764: 	    $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked /> Use the CODE <b><tt>".$$scan_record{'scantron.CODE'}."</tt></b> that is was on the paper, ignoring the error.</label>");
                   4765: 	    $r->print("\n<br />");
                   4766: 	}
1.194     albertel 4767: 
1.188     albertel 4768: 	$r->print(<<ENDSCRIPT);
                   4769: <script type="text/javascript">
                   4770: function change_radio(field) {
1.190     albertel 4771:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 4772:     var i;
                   4773:     for (i=0;i<slct.length;i++) {
                   4774:         if (slct[i].value==field) { slct[i].checked=true; }
                   4775:     }
                   4776: }
                   4777: </script>
                   4778: ENDSCRIPT
1.187     albertel 4779: 	my $href="/adm/pickcode?".
                   4780: 	   "form=".&Apache::lonnet::escape("scantronupload").
1.257     albertel 4781: 	   "&scantron_format=".&Apache::lonnet::escape($env{'form.scantron_format'}).
                   4782: 	   "&scantron_CODElist=".&Apache::lonnet::escape($env{'form.scantron_CODElist'}).
1.187     albertel 4783: 	   "&curCODE=".&Apache::lonnet::escape($$scan_record{'scantron.CODE'}).
1.257     albertel 4784: 	   "&scantron_selectfile=".&Apache::lonnet::escape($env{'form.scantron_selectfile'});
1.272     albertel 4785: 	$r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_found' /> <a target='_blank' href='$href'>Select</a> a CODE from the list of all CODEs and use it.</label> Selected CODE is <input readonly='true' type='text' size='8' name='scantron_CODE_selectedvalue' onfocus=\"javascript:change_radio('use_found')\" onchange=\"javascript:change_radio('use_found')\" />");
1.187     albertel 4786: 	$r->print("\n<br />");
1.272     albertel 4787: 	$r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_typed' /> Use </label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" /> as the CODE.");
1.187     albertel 4788: 	$r->print("\n<br /><br />");
1.157     albertel 4789:     } elsif ($error eq 'doublebubble') {
                   4790: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   4791: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   4792: 		  join(',',@{$arg}).'" />');
1.242     albertel 4793: 	$r->print($message);
1.157     albertel 4794: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   4795: 	foreach my $question (@{$arg}) {
                   4796: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   4797: 	    &scantron_bubble_selector($r,$scan_config,$question,split('',$selected));
                   4798: 	}
                   4799:     } elsif ($error eq 'missingbubble') {
                   4800: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 4801: 	$r->print($message);
1.157     albertel 4802: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   4803: 	$r->print("Some questions have no scanned bubbles\n");
                   4804: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   4805: 		  join(',',@{$arg}).'" />');
                   4806: 	foreach my $question (@{$arg}) {
                   4807: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   4808: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   4809: 	}
                   4810:     } else {
                   4811: 	$r->print("\n<ul>");
                   4812:     }
                   4813:     $r->print("\n</li></ul>");
                   4814: 
                   4815: }
                   4816: 
                   4817: sub scantron_bubble_selector {
                   4818:     my ($r,$scan_config,$quest,@selected)=@_;
                   4819:     my $max=$$scan_config{'Qlength'};
1.274     albertel 4820: 
                   4821:     my $scmode=$$scan_config{'Qon'};
                   4822:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   4823: 
1.157     albertel 4824:     my @alphabet=('A'..'Z');
                   4825:     $r->print("<table border='1'><tr><td rowspan='2'>$quest</td>");
                   4826:     for (my $i=0;$i<$max+1;$i++) {
1.274     albertel 4827: 	$r->print("\n".'<td align="center">');
1.157     albertel 4828: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   4829: 	else { $r->print('&nbsp;'); }
                   4830: 	$r->print('</td>');
                   4831:     }
1.274     albertel 4832:     $r->print('</tr><tr>');
1.157     albertel 4833:     for (my $i=0;$i<$max;$i++) {
1.274     albertel 4834: 	$r->print("\n".
                   4835: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
1.272     albertel 4836: 		  $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
1.157     albertel 4837:     }
1.272     albertel 4838:     $r->print('<td><label><input type="radio" name="scantron_correct_Q_'.
                   4839: 	      $quest.'" value="none" /> No bubble </label></td>');
1.157     albertel 4840:     $r->print('</tr></table>');
                   4841: }
                   4842: 
1.194     albertel 4843: sub num_matches {
                   4844:     my ($orig,$code) = @_;
                   4845:     my @code=split(//,$code);
                   4846:     my @orig=split(//,$orig);
                   4847:     my $same=0;
                   4848:     for (my $i=0;$i<scalar(@code);$i++) {
                   4849: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   4850:     }
                   4851:     return $same;
                   4852: }
                   4853: 
                   4854: sub scantron_get_closely_matching_CODEs {
                   4855:     my ($allcodes,$CODE)=@_;
                   4856:     my @CODEs;
                   4857:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   4858: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   4859:     }
                   4860: 
                   4861:     return ($#CODEs,$CODEs[-1]);
                   4862: }
                   4863: 
                   4864: sub get_codes {
1.257     albertel 4865:     my $old_name=$env{'form.scantron_CODElist'};
                   4866:     my $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4867:     my $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
1.194     albertel 4868:     my %result=&Apache::lonnet::get('CODEs',[$old_name],$cdom,$cnum);
                   4869:     my %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   4870:     return %allcodes;
                   4871: }
                   4872: 
1.157     albertel 4873: sub scantron_validate_CODE {
                   4874:     my ($r,$currentphase) = @_;
1.257     albertel 4875:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 4876:     if ($scantron_config{'CODElocation'} &&
                   4877: 	$scantron_config{'CODEstart'} &&
                   4878: 	$scantron_config{'CODElength'}) {
1.257     albertel 4879: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 4880: 	    &FIXME_blow_up()
                   4881: 	}
                   4882:     } else {
                   4883: 	return (0,$currentphase+1);
                   4884:     }
                   4885:     
                   4886:     my %usedCODEs;
                   4887: 
1.194     albertel 4888:     my %allcodes=&get_codes();
1.186     albertel 4889: 
                   4890:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4891:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 4892: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 4893: 	if ($line=~/^[\s\cz]*$/) { next; }
                   4894: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   4895: 						 $scan_data);
                   4896: 	my $CODE=$$scan_record{'scantron.CODE'};
                   4897: 	my $error=0;
1.224     albertel 4898: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   4899: 	    &scantron_get_correction($r,$i,$scan_record,
                   4900: 				     \%scantron_config,
                   4901: 				     $line,'incorrectCODE',\%allcodes);
                   4902: 	    return(1,$currentphase);
                   4903: 	}
1.221     albertel 4904: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   4905: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 4906: 	    &scantron_get_correction($r,$i,$scan_record,
                   4907: 				     \%scantron_config,
1.194     albertel 4908: 				     $line,'incorrectCODE',\%allcodes);
                   4909: 	    return(1,$currentphase);
1.186     albertel 4910: 	}
1.214     albertel 4911: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 4912: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 4913: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 4914: 	    &scantron_get_correction($r,$i,$scan_record,
                   4915: 				     \%scantron_config,
1.194     albertel 4916: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   4917: 	    return(1,$currentphase);
1.186     albertel 4918: 	}
1.194     albertel 4919: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 4920:     }
1.157     albertel 4921:     return (0,$currentphase+1);
                   4922: }
                   4923: 
                   4924: sub scantron_validate_doublebubble {
                   4925:     my ($r,$currentphase) = @_;
                   4926:     #get student info
                   4927:     my $classlist=&Apache::loncoursedata::get_classlist();
                   4928:     my %idmap=&username_to_idmap($classlist);
                   4929: 
                   4930:     #get scantron line setup
1.257     albertel 4931:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 4932:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4933:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 4934: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 4935: 	if ($line=~/^[\s\cz]*$/) { next; }
                   4936: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   4937: 						 $scan_data);
                   4938: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   4939: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   4940: 				 'doublebubble',
                   4941: 				 $$scan_record{'scantron.doubleerror'});
                   4942:     	return (1,$currentphase);
                   4943:     }
                   4944:     return (0,$currentphase+1);
                   4945: }
                   4946: 
1.191     albertel 4947: sub scantron_get_maxbubble {
                   4948:     my ($r)=@_;
1.257     albertel 4949:     if (defined($env{'form.scantron_maxbubble'}) &&
                   4950: 	$env{'form.scantron_maxbubble'}) {
                   4951: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 4952:     }
                   4953:     my $navmap=Apache::lonnavmaps::navmap->new();
                   4954:     my (undef,undef,$sequence)=
1.257     albertel 4955: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.191     albertel 4956:     my $map=$navmap->getResourceByUrl($sequence);
                   4957:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   4958:     &Apache::lonnet::delenv('form.counter');
                   4959:     foreach my $resource (@resources) {
1.234     albertel 4960: 	my $result=&Apache::lonnet::ssi($resource->src().'?symb='.&Apache::lonnet::escape($resource->symb()));
1.191     albertel 4961:     }
                   4962:     &Apache::lonnet::delenv('scantron\.');
1.257     albertel 4963:     my $envfile=$env{'user.environment'};
1.191     albertel 4964:     $envfile=~/\/([^\/]+)\.id$/;
                   4965:     $envfile=$1;
                   4966:     &Apache::lonnet::transfer_profile_to_env($r->dir_config('lonIDsDir'),
                   4967: 					     $envfile);
1.257     albertel 4968:     $env{'form.scantron_maxbubble'}=$env{'form.counter'}-1;
                   4969:     return $env{'form.scantron_maxbubble'};
1.191     albertel 4970: }
                   4971: 
1.157     albertel 4972: sub scantron_validate_missingbubbles {
                   4973:     my ($r,$currentphase) = @_;
                   4974:     #get student info
                   4975:     my $classlist=&Apache::loncoursedata::get_classlist();
                   4976:     my %idmap=&username_to_idmap($classlist);
                   4977: 
                   4978:     #get scantron line setup
1.257     albertel 4979:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 4980:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 4981:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 4982:     if (!$max_bubble) { $max_bubble=2**31; }
                   4983:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 4984: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 4985: 	if ($line=~/^[\s\cz]*$/) { next; }
                   4986: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   4987: 						 $scan_data);
                   4988: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   4989: 	my @to_correct;
                   4990: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   4991: 	    if ($missing > $max_bubble) { next; }
                   4992: 	    push(@to_correct,$missing);
                   4993: 	}
                   4994: 	if (@to_correct) {
                   4995: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   4996: 				     $line,'missingbubble',\@to_correct);
                   4997: 	    return (1,$currentphase);
                   4998: 	}
                   4999: 
                   5000:     }
                   5001:     return (0,$currentphase+1);
                   5002: }
                   5003: 
1.82      albertel 5004: sub scantron_process_students {
1.75      albertel 5005:     my ($r) = @_;
1.257     albertel 5006:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.81      albertel 5007:     my ($symb,$url)=&get_symb_and_url($r);
                   5008:     if (!$symb) {return '';}
                   5009:     my $default_form_data=&defaultFormData($symb,$url);
1.82      albertel 5010: 
1.257     albertel 5011:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5012:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 5013:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5014:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 5015:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 5016:     my $map=$navmap->getResourceByUrl($sequence);
                   5017:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 5018: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 5019:     my $result= <<SCANTRONFORM;
1.81      albertel 5020: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   5021:   <input type="hidden" name="command" value="scantron_configphase" />
                   5022:   $default_form_data
                   5023: SCANTRONFORM
1.82      albertel 5024:     $r->print($result);
                   5025: 
                   5026:     my @delayqueue;
1.140     albertel 5027:     my %completedstudents;
                   5028:     
1.200     albertel 5029:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 5030:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 5031:  				    'Scantron Progress',$count,
1.195     albertel 5032: 				    'inline',undef,'scantronupload');
1.140     albertel 5033:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   5034: 					  'Processing first student');
                   5035:     my $start=&Time::HiRes::time();
1.158     albertel 5036:     my $i=-1;
1.200     albertel 5037:     my ($uname,$udom,$started);
1.157     albertel 5038:     while ($i<$scanlines->{'count'}) {
                   5039:  	($uname,$udom)=('','');
                   5040:  	$i++;
1.200     albertel 5041:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5042:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 5043: 	if ($started) {
                   5044: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   5045: 						     'last student');
                   5046: 	}
                   5047: 	$started=1;
1.157     albertel 5048:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5049:  						 $scan_data);
                   5050:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   5051:  					      \%idmap,$i)) {
                   5052:   	    &scantron_add_delay(\@delayqueue,$line,
                   5053:  				'Unable to find a student that matches',1);
                   5054:  	    next;
                   5055:   	}
                   5056:  	if (exists $completedstudents{$uname}) {
                   5057:  	    &scantron_add_delay(\@delayqueue,$line,
                   5058:  				'Student '.$uname.' has multiple sheets',2);
                   5059:  	    next;
                   5060:  	}
                   5061:   	($uname,$udom)=split(/:/,$uname);
                   5062:   	&Apache::lonnet::delenv('form.counter');
                   5063:   	&Apache::lonnet::appenv(%$scan_record);
1.161     albertel 5064: 	
                   5065: 	my $i=0;
1.83      albertel 5066: 	foreach my $resource (@resources) {
1.85      albertel 5067: 	    $i++;
1.193     albertel 5068: 	    my %form=('submitted'     =>'scantron',
                   5069: 		      'grade_target'  =>'grade',
                   5070: 		      'grade_username'=>$uname,
                   5071: 		      'grade_domain'  =>$udom,
1.257     albertel 5072: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 5073: 		      'grade_symb'    =>$resource->symb());
                   5074: 	    if (exists($scan_record->{'scantron.CODE'}) &&
                   5075: 		$scan_record->{'scantron.CODE'}) {
                   5076: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 5077: 	    } else {
                   5078: 		$form{'CODE'}='';
1.193     albertel 5079: 	    }
                   5080: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 5081: 	    if ($result ne '') {
                   5082: 		&Apache::lonnet::logthis("scantron grading error -> $result");
1.257     albertel 5083: 		&Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
1.227     albertel 5084: 	    }
1.213     albertel 5085: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 5086: 	}
1.140     albertel 5087: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 5088: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 5089:     } continue {
1.85      albertel 5090: 	&Apache::lonnet::delenv('form.counter');
1.83      albertel 5091: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 5092:     }
1.140     albertel 5093:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 5094: #    my $lasttime = &Time::HiRes::time()-$start;
                   5095: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 5096: 
1.200     albertel 5097:     $r->print("</form>");
1.157     albertel 5098:     $r->print(&show_grading_menu_form($symb,$url));
                   5099:     return '';
1.75      albertel 5100: }
1.157     albertel 5101: 
                   5102: sub scantron_upload_scantron_data {
                   5103:     my ($r)=@_;
1.257     albertel 5104:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 5105:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 5106: 							  'domainid',
                   5107: 							  'coursename');
1.257     albertel 5108:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 5109: 						   'domainid');
1.173     albertel 5110:     my $default_form_data=&defaultFormData(&get_symb_and_url($r,1));
1.157     albertel 5111:     $r->print(<<UPLOAD);
                   5112: <script type="text/javascript" language="javascript">
                   5113:     function checkUpload(formname) {
                   5114: 	if (formname.upfile.value == "") {
                   5115: 	    alert("Please use the browse button to select a file from your local directory.");
                   5116: 	    return false;
                   5117: 	}
                   5118: 	formname.submit();
                   5119:     }
                   5120: </script>
                   5121: 
                   5122: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 5123: $default_form_data
1.181     albertel 5124: <table>
                   5125: <tr><td>$select_link </td></tr>
                   5126: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   5127: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   5128: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   5129: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   5130: </table>
1.157     albertel 5131: <input name='command' value='scantronupload_save' type='hidden' />
                   5132: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   5133: </form>
                   5134: UPLOAD
                   5135:     return '';
                   5136: }
                   5137: 
                   5138: sub scantron_upload_scantron_data_save {
                   5139:     my($r)=@_;
1.182     albertel 5140:     my ($symb,$url)=&get_symb_and_url($r,1);
                   5141:     my $doanotherupload=
                   5142: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   5143: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   5144: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   5145: 	'</form>'."\n";
1.257     albertel 5146:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 5147: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 5148: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 5149: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 5150: 	if ($symb) {
                   5151: 	    $r->print(&show_grading_menu_form($symb,$url));
                   5152: 	} else {
                   5153: 	    $r->print($doanotherupload);
                   5154: 	}
1.162     albertel 5155: 	return '';
                   5156:     }
1.257     albertel 5157:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       5158:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 5159:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 5160:     #FIXME
                   5161:     #copied from lonnet::userfileupload()
                   5162:     #make that function able to target a specified course
                   5163:     # Replace Windows backslashes by forward slashes
                   5164:     $fname=~s/\\/\//g;
                   5165:     # Get rid of everything but the actual filename
                   5166:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   5167:     # Replace spaces by underscores
                   5168:     $fname=~s/\s+/\_/g;
                   5169:     # Replace all other weird characters by nothing
                   5170:     $fname=~s/[^\w\.\-]//g;
                   5171:     # See if there is anything left
                   5172:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       5173:     my $uploadedfile=$fname;
1.157     albertel 5174:     $fname='scantron_orig_'.$fname;
1.257     albertel 5175:     if (length($env{'form.upfile'}) < 2) {
                   5176: 	$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 5177:     } else {
1.275   ! albertel 5178: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 5179: 	if ($result =~ m|^/uploaded/|) {
1.257     albertel 5180: 	    $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 5181: 	} else {
1.257     albertel 5182: 	    $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 5183: 	}
                   5184:     }
1.174     albertel 5185:     if ($symb) {
1.209     ng       5186: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 5187:     } else {
1.182     albertel 5188: 	$r->print($doanotherupload);
1.174     albertel 5189:     }
1.157     albertel 5190:     return '';
                   5191: }
                   5192: 
1.202     albertel 5193: sub valid_file {
                   5194:     my ($requested_file)=@_;
                   5195:     foreach my $filename (sort(&scantron_filenames())) {
                   5196: 	&Apache::lonnet::logthis("$requested_file  $filename");
                   5197: 	if ($requested_file eq $filename) { return 1; }
                   5198:     }
                   5199:     return 0;
                   5200: }
                   5201: 
                   5202: sub scantron_download_scantron_data {
                   5203:     my ($r)=@_;
                   5204:     my $default_form_data=&defaultFormData(&get_symb_and_url($r,1));
1.257     albertel 5205:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5206:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5207:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 5208:     if (! &valid_file($file)) {
                   5209: 	$r->print(<<ERROR);
                   5210: 	<p>
                   5211: 	    The requested file name was invalid.
                   5212:         </p>
                   5213: ERROR
                   5214: 	$r->print(&show_grading_menu_form(&get_symb_and_url($r,1)));
                   5215: 	return;
                   5216:     }
                   5217:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   5218:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   5219:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   5220:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   5221:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   5222:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   5223:     $r->print(<<DOWNLOAD);
                   5224:     <p>
                   5225: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   5226:     </p>
                   5227:     <p>
                   5228: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   5229:     </p>
                   5230:     <p>
                   5231: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   5232:     </p>
                   5233: DOWNLOAD
                   5234:     $r->print(&show_grading_menu_form(&get_symb_and_url($r,1)));
                   5235:     return '';
                   5236: }
1.157     albertel 5237: 
1.75      albertel 5238: #-------- end of section for handling grading scantron forms -------
                   5239: #
                   5240: #-------------------------------------------------------------------
                   5241: 
1.72      ng       5242: #-------------------------- Menu interface -------------------------
                   5243: #
                   5244: #--- Show a Grading Menu button - Calls the next routine ---
                   5245: sub show_grading_menu_form {
                   5246:     my ($symb,$url)=@_;
1.125     ng       5247:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.72      ng       5248: 	'<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
                   5249: 	'<input type="hidden" name="url" value="'.$url.'" />'."\n".
1.257     albertel 5250: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       5251: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   5252: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   5253: 	'</form>'."\n";
                   5254:     return $result;
                   5255: }
                   5256: 
1.77      ng       5257: # -- Retrieve choices for grading form
                   5258: sub savedState {
                   5259:     my %savedState = ();
1.257     albertel 5260:     if ($env{'form.saveState'}) {
                   5261: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       5262: 	    my ($key,$value) = split(/=/,$_,2);
                   5263: 	    $savedState{$key} = $value;
                   5264: 	}
                   5265:     }
                   5266:     return \%savedState;
                   5267: }
1.76      ng       5268: 
1.72      ng       5269: #--- Displays the main menu page -------
                   5270: sub gradingmenu {
                   5271:     my ($request) = @_;
                   5272:     my ($symb,$url)=&get_symb_and_url($request);
                   5273:     if (!$symb) {return '';}
1.76      ng       5274:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       5275: 
                   5276:     $request->print(<<GRADINGMENUJS);
                   5277: <script type="text/javascript" language="javascript">
1.116     ng       5278:     function checkChoice(formname,val,cmdx) {
                   5279: 	if (val <= 2) {
                   5280: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       5281: 	    var cmdsave = cmd;
1.116     ng       5282: 	} else {
                   5283: 	    cmd = cmdx;
1.118     ng       5284: 	    cmdsave = 'submission';
1.116     ng       5285: 	}
                   5286: 	formname.command.value = cmd;
1.118     ng       5287: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 5288: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       5289: 	if (val < 5) formname.submit();
                   5290: 	if (val == 5) {
1.72      ng       5291: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   5292: 	    formname.submit();
                   5293: 	}
1.238     albertel 5294: 	if (val < 7) formname.submit();
1.72      ng       5295:     }
                   5296: 
                   5297:     function checkReceiptNo(formname,nospace) {
                   5298: 	var receiptNo = formname.receipt.value;
                   5299: 	var checkOpt = false;
                   5300: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   5301: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   5302: 	if (checkOpt) {
                   5303: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   5304: 	    formname.receipt.value = "";
                   5305: 	    formname.receipt.focus();
                   5306: 	    return false;
                   5307: 	}
                   5308: 	return true;
                   5309:     }
                   5310: </script>
                   5311: GRADINGMENUJS
1.118     ng       5312:     &commonJSfunctions($request);
                   5313:     my $result='<h3>&nbsp;<font color="#339933">Manual Grading/View Submission</font></h3>';
1.122     ng       5314:     my ($table,undef,$hdgrade) = &showResourceInfo($url,$probTitle);
1.118     ng       5315:     $result.=$table;
1.76      ng       5316:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       5317:     my $savedState = &savedState();
1.118     ng       5318:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       5319:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       5320:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       5321:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       5322: 
                   5323:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   5324: 	'<input type="hidden" name="symb"        value="'.$symb.'" />'."\n".
                   5325: 	'<input type="hidden" name="url"         value="'.$url.'" />'."\n".
                   5326: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   5327: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       5328: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       5329: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       5330: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       5331: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   5332: 
1.116     ng       5333:     $result.='<table width="100%" border=0><tr><td bgcolor=#777777>'."\n".
                   5334: 	'<table width=100% border=0><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
1.72      ng       5335: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       5336: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   5337: 
                   5338:     $result.='<table width="100%" border=0>';
                   5339:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.167     sakharuk 5340: 	'&nbsp;'.&mt('Select Section').': <select name="section">'."\n";
1.116     ng       5341:     if (ref($sections)) {
1.155     albertel 5342: 	foreach (sort (@$sections)) {
                   5343: 	    $result.='<option value="'.$_.'" '.
                   5344: 		($saveSec eq $_ ? 'selected="on"':'').'>'.$_.'</option>'."\n";
                   5345: 	}
1.116     ng       5346:     }
1.238     albertel 5347:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="on"' : ''). '>all</option></select> &nbsp; ';
1.116     ng       5348: 
1.167     sakharuk 5349:     $result.=&mt('Student Status').':</b>'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
1.72      ng       5350: 
1.116     ng       5351:     $result.='</td></tr>';
                   5352: 
1.118     ng       5353:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
                   5354: 	'<input type="radio" name="radioChoice" value="submission" '.
1.167     sakharuk 5355: 	($saveCmd eq 'submission' ? 'checked' : '').'> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
                   5356: 	' <select name="submitonly">'.
1.145     albertel 5357: 	'<option value="yes" '.
                   5358: 	($saveSub eq 'yes' ? 'selected="on"' : '').'>with submissions</option>'.
                   5359: 	'<option value="graded" '.
                   5360: 	($saveSub eq 'graded' ? 'selected="on"' : '').'>with ungraded submissions</option>'.
1.156     albertel 5361: 	'<option value="incorrect" '.
                   5362: 	($saveSub eq 'incorrect' ? 'selected="on"' : '').'>with incorrect submissions</option>'.
1.145     albertel 5363: 	'<option value="all" '.
                   5364: 	($saveSub eq 'all' ? 'selected="on"' : '').'>with any status</option></select></td></tr>'."\n";
1.72      ng       5365: 
1.116     ng       5366:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
                   5367: 	'<input type="radio" name="radioChoice" value="viewgrades" '.
1.76      ng       5368: 	($saveCmd eq 'viewgrades' ? 'checked' : '').'> '.
1.118     ng       5369: 	'<b>Current Resource:</b> For all students in selected section or course</td></tr>'."\n";
1.72      ng       5370: 
1.118     ng       5371:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
                   5372: 	'<input type="radio" name="radioChoice" value="pickStudentPage" '.
                   5373: 	($saveCmd eq 'pickStudentPage' ? 'checked' : '').'> '.
                   5374: 	'The <b>complete</b> set/page/sequence: For one student</td></tr>'."\n";
1.46      ng       5375: 
1.116     ng       5376:     $result.='<tr bgcolor="#ffffe6"><td><br />'.
1.126     ng       5377: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       5378: 	'</td></tr></table>'."\n";
                   5379: 
                   5380:     $result.='</td><td valign="top">';
                   5381: 
                   5382:     $result.='<table width="100%" border=0>';
                   5383:     $result.='<tr bgcolor="#ffffe6"><td>'.
1.184     www      5384: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   5385: 	' '.&mt('scores from file').' </td></tr>'."\n";
1.72      ng       5386: 
1.75      albertel 5387:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.116     ng       5388: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
1.184     www      5389: 	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
1.75      albertel 5390: 
1.257     albertel 5391:     if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
1.72      ng       5392: 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.184     www      5393: 	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   5394: 	    ' '.&mt('receipt').': '.
1.257     albertel 5395: 	    &Apache::lonnet::recprefix($env{'request.course.id'}).
1.72      ng       5396: 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')">'.
                   5397: 	    '</td></tr>'."\n";
                   5398:     } 
1.238     albertel 5399:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   5400: 	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   5401: 	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
1.44      ng       5402: 
1.116     ng       5403:     $result.='</form></td></tr></table>'."\n".
1.72      ng       5404: 	'</td></tr></table>'."\n".
                   5405: 	'</td></tr></table>'."\n";
1.44      ng       5406:     return $result;
1.2       albertel 5407: }
                   5408: 
1.1       albertel 5409: sub handler {
1.41      ng       5410:     my $request=$_[0];
1.102     albertel 5411: 
1.103     albertel 5412:     undef(%perm);
1.257     albertel 5413:     if ($env{'browser.mathml'}) {
1.141     www      5414: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       5415:     } else {
1.141     www      5416: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       5417:     }
                   5418:     $request->send_http_header;
1.44      ng       5419:     return '' if $request->header_only;
1.41      ng       5420:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.257     albertel 5421:     my $url=$env{'form.url'};
                   5422:     my $symb=$env{'form.symb'};
1.160     albertel 5423:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   5424:     my $command=$commands[0];
                   5425:     if ($#commands > 0) {
                   5426: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   5427:     }
1.41      ng       5428:     if (!$url) {
                   5429: 	my ($temp1,$temp2);
1.257     albertel 5430: 	($temp1,$temp2,$env{'form.url'})=&Apache::lonnet::decode_symb($symb);
                   5431: 	$url = $env{'form.url'};
1.41      ng       5432:     }
                   5433:     &send_header($request);
1.157     albertel 5434:     if ($url eq '' && $symb eq '' && $command eq '') {
1.257     albertel 5435: 	if ($env{'user.adv'}) {
                   5436: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   5437: 		($env{'form.codethree'})) {
                   5438: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   5439: 		    $env{'form.codethree'};
1.41      ng       5440: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   5441: 		    &Apache::lonnet::checkin($token);
                   5442: 		if ($tsymb) {
1.137     albertel 5443: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       5444: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 5445: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   5446: 					  ('grade_username' => $tuname,
                   5447: 					   'grade_domain' => $tudom,
                   5448: 					   'grade_courseid' => $tcrsid,
                   5449: 					   'grade_symb' => $tsymb)));
1.41      ng       5450: 		    } else {
1.45      ng       5451: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 5452: 		    }
1.41      ng       5453: 		} else {
1.45      ng       5454: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       5455: 		}
1.14      www      5456: 	    } else {
1.41      ng       5457: 		$request->print(&Apache::lonxml::tokeninputfield());
                   5458: 	    }
                   5459: 	}
                   5460:     } else {
1.257     albertel 5461: 	if (!($perm{'vgr'}=&Apache::lonnet::allowed('vgr',$env{'request.course.id'}))) {
                   5462: 	    if ($perm{'vgr'}=&Apache::lonnet::allowed('vgr',$env{'request.course.id'}.'/'.$env{'request.course.sec'})) {
                   5463: 		$perm{'vgr_section'}=$env{'request.course.sec'};
1.102     albertel 5464: 	    } else {
1.103     albertel 5465: 		delete($perm{'vgr'});
1.102     albertel 5466: 	    }
                   5467: 	}
1.257     albertel 5468: 	if (!($perm{'mgr'}=&Apache::lonnet::allowed('mgr',$env{'request.course.id'}))) {
                   5469: 	    if ($perm{'mgr'}=&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.'/'.$env{'request.course.sec'})) {
                   5470: 		$perm{'mgr_section'}=$env{'request.course.sec'};
1.102     albertel 5471: 	    } else {
1.103     albertel 5472: 		delete($perm{'mgr'});
1.102     albertel 5473: 	    }
                   5474: 	}
1.104     albertel 5475: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 5476: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 5477: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       5478: 	    &pickStudentPage($request);
1.103     albertel 5479: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       5480: 	    &displayPage($request);
1.104     albertel 5481: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       5482: 	    &updateGradeByPage($request);
1.104     albertel 5483: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       5484: 	    &processGroup($request);
1.104     albertel 5485: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.41      ng       5486: 	    $request->print(&gradingmenu($request));
1.104     albertel 5487: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       5488: 	    $request->print(&viewgrades($request));
1.104     albertel 5489: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       5490: 	    $request->print(&processHandGrade($request));
1.106     albertel 5491: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       5492: 	    $request->print(&editgrades($request));
1.106     albertel 5493: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       5494: 	    $request->print(&verifyreceipt($request));
1.106     albertel 5495: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       5496: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 5497: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       5498: 	    $request->print(&csvupload($request));
1.106     albertel 5499: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       5500: 	    $request->print(&csvuploadmap($request));
1.246     albertel 5501: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 5502: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 5503: 		$request->print(&csvuploadoptions($request));
1.41      ng       5504: 	    } else {
1.257     albertel 5505: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   5506: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       5507: 		} else {
1.257     albertel 5508: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       5509: 		}
                   5510: 		$request->print(&csvuploadmap($request));
                   5511: 	    }
1.246     albertel 5512: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   5513: 	    $request->print(&csvuploadassign($request));
1.106     albertel 5514: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 5515: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 5516:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   5517:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 5518: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   5519: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 5520: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 5521: 	    $request->print(&scantron_process_students($request));
1.157     albertel 5522:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 5523:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   5524: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 5525:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 5526:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 5527:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   5528: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 5529:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 5530:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 5531: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5532:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 5533: 	} elsif ($command) {
1.157     albertel 5534: 	    $request->print("Access Denied ($command)");
1.26      albertel 5535: 	}
1.2       albertel 5536:     }
1.41      ng       5537:     &send_footer($request);
1.44      ng       5538:     return '';
                   5539: }
                   5540: 
                   5541: sub send_header {
                   5542:     my ($request)= @_;
                   5543:     $request->print(&Apache::lontexconvert::header());
                   5544: #  $request->print("
                   5545: #<script>
                   5546: #remotewindow=open('','homeworkremote');
                   5547: #remotewindow.close();
                   5548: #</script>"); 
1.47      www      5549:     $request->print(&Apache::loncommon::bodytag('Grading'));
1.157     albertel 5550:     $request->rflush();
1.44      ng       5551: }
                   5552: 
                   5553: sub send_footer {
                   5554:     my ($request)= @_;
1.212     albertel 5555:     $request->print('</body></html>');
1.1       albertel 5556: }
                   5557: 
                   5558: 1;
                   5559: 
1.13      albertel 5560: __END__;

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