File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.243: download - view: text, annotated - select for diffs
Sat Feb 12 02:37:00 2005 UTC (19 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- upload scores now accpets student IDs as well as usernames

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

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