File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.248: download - view: text, annotated - select for diffs
Fri Feb 18 23:36:12 2005 UTC (19 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#3896 & 3895, mishandling the ungraded and incorrect situations

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

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