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

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

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