File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.171: download - view: text, annotated - select for diffs
Wed Jan 28 16:25:05 2004 UTC (20 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- fix up message for when no submissions found in specif filter modes BUG#2470

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

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