File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.167: download - view: text, annotated - select for diffs
Fri Dec 5 14:59:51 2003 UTC (20 years, 4 months ago) by sakharuk
Branches: MAIN
CVS tags: HEAD
Starting localization.

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

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