File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.234: download - view: text, annotated - select for diffs
Fri Dec 3 23:54:58 2004 UTC (19 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
 BUG#3656, bubble counting could be off

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

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