File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.169: download - view: text, annotated - select for diffs
Fri Dec 5 19:54:51 2003 UTC (20 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- when viewing SUBM for multiple students only the first 'Grade Student' button worked BUG#2418

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

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