File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.166: download - view: text, annotated - select for diffs
Thu Dec 4 23:23:16 2003 UTC (20 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- Fixes BUG#2423 which was caused by the fix to BUG#2253, now preserves student returns and line wraps things correctly on the screen.

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

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