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

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

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