File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.204.2.5: download - view: text, annotated - select for diffs
Fri Sep 24 21:09:52 2004 UTC (19 years, 7 months ago) by albertel
Branches: version_1_2_X
Diff to branchpoint 1.204: preferred, unified
- backport 1.214

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

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