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

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

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