File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.249: download - view: text, annotated - select for diffs
Mon Feb 28 21:18:08 2005 UTC (19 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- most of bug #2652, Written by Ray Batchelor

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

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