File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.176: download - view: text, annotated - select for diffs
Tue Feb 17 16:45:58 2004 UTC (20 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#2735 - select roles domain as the def domain wen fixing errors in scantron grading

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

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