File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.168: download - view: text, annotated - select for diffs
Fri Dec 5 19:40:56 2003 UTC (20 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#2424, need to make sure we always get the correct weight, so invalidata param cache before doing EXT

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

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