File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.179: download - view: text, annotated - select for diffs
Thu Mar 4 14:09:47 2004 UTC (20 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- makes grading problems with many possible points look prettier.

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

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