File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.258: download - view: text, annotated - select for diffs
Thu Apr 7 07:03:23 2005 UTC (19 years ago) by albertel
Branches: MAIN
CVS tags: HEAD
- missed a couple of ENV -> env

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.258 2005/04/07 07:03:23 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>';
  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').'&nbsp;Section/Group</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 @parts_graded;
 2117:     my %newrecord  = ();
 2118:     my ($pts,$wgt) = ('','');
 2119:     foreach (split(/:/,$env{'form.partlist'.$newflg})) {
 2120: 	#collaborator may vary for different parts
 2121: 	if ($submitter && $_ ne $part) { next; }
 2122: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$_};
 2123: 	if ($dropMenu eq 'excused') {
 2124: 	    if ($record{'resource.'.$_.'.solved'} ne 'excused') {
 2125: 		$newrecord{'resource.'.$_.'.solved'} = 'excused';
 2126: 		if (exists($record{'resource.'.$_.'.awarded'})) {
 2127: 		    $newrecord{'resource.'.$_.'.awarded'} = '';
 2128: 		}
 2129: 	    $newrecord{'resource.'.$_.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2130: 	    }
 2131: 	} elsif ($dropMenu eq 'reset status'
 2132: 		 && exists($record{'resource.'.$_.'.solved'})) { #don't bother if no old records -> no attempts
 2133: 	    foreach my $key (keys (%record)) {
 2134: 		if ($key=~/^resource\.\Q$_\E\./) { $newrecord{$key} = ''; }
 2135: 	    }
 2136: 	    $newrecord{'resource.'.$_.'.regrader'}=
 2137: 		"$env{'user.name'}:$env{'user.domain'}";
 2138: 	} elsif ($dropMenu eq '') {
 2139: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$_} ne '' ? 
 2140: 		    $env{'form.GD_BOX'.$newflg.'_'.$_} : 
 2141: 		    $env{'form.RADVAL'.$newflg.'_'.$_});
 2142: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$_} eq '') {
 2143: 		next;
 2144: 	    }
 2145: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$_} eq '' ? 1 : 
 2146: 		$env{'form.WGT'.$newflg.'_'.$_};
 2147: 	    my $partial= $pts/$wgt;
 2148: 	    if ($partial eq $record{'resource.'.$_.'.awarded'}) {
 2149: 		#do not update score for part if not changed.
 2150: 		next;
 2151: 	    } else {
 2152: 	        push @parts_graded, $_;
 2153: 	    }
 2154: 	    if ($record{'resource.'.$_.'.awarded'} ne $partial) {
 2155: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial;
 2156: 	    }
 2157: 	    my $reckey = 'resource.'.$_.'.solved';
 2158: 	    if ($partial == 0) {
 2159: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2160: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2161: 		}
 2162: 	    } else {
 2163: 		if ($record{$reckey} ne 'correct_by_override') {
 2164: 		    $newrecord{$reckey} = 'correct_by_override';
 2165: 		}
 2166: 	    }	    
 2167: 	    if ($submitter && 
 2168: 		($record{'resource.'.$_.'.submitted_by'} ne $submitter)) {
 2169: 		$newrecord{'resource.'.$_.'.submitted_by'} = $submitter;
 2170: 	    }
 2171: 	    $newrecord{'resource.'.$_.'.regrader'}=
 2172: 		"$env{'user.name'}:$env{'user.domain'}";
 2173: 	}
 2174:     }
 2175:     if (scalar(keys(%newrecord)) > 0) {
 2176:         &version_portfiles(\%record, \@parts_graded, $env{'request.course.id'}, $symb, $domain, $stuname);
 2177: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2178: 				$env{'request.course.id'},$domain,$stuname);
 2179:     }
 2180:     return '',$pts,$wgt;
 2181: }
 2182: 
 2183: # ----------- Handles creating versions for portfolio files as answers
 2184: sub version_portfiles {
 2185:     my ($record, $parts_graded, $courseid, $symb, $domain, $stuname) = @_;
 2186:     my $parts = join('|', @$parts_graded);
 2187:     my $portfolio_root = &Apache::loncommon::propath($domain,
 2188: 						 $stuname).
 2189: 						'/userfiles/portfolio';
 2190:     foreach my $key(keys %$record) {
 2191:         if ($key =~ /^resource\.($parts)\./ && $key =~ /\.portfiles$/) {
 2192:             my @portfiles = split(/,/,$$record{$key});
 2193:             foreach my $file (@portfiles) {
 2194:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*$)/);
 2195:                 my $version = 0;
 2196:                 my @answer_file_parts = split(/\./, $answer_file);
 2197:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stuname,$portfolio_root);
 2198:                 my @file_names;
 2199:                 my @file_name_parts;
 2200:                 foreach my $row (@dir_list) {
 2201:                     @file_names = split(/\&/,$row,2);
 2202:                     @file_name_parts = split(/\./, $file_names[0]);
 2203:                     # ($file_name_parts[scalar @file_name_parts] eq $answer_file_parts[scalar @answer_file_parts])
 2204:                     if (($file_name_parts[0] eq $answer_file_parts[0]) && 
 2205:                         ($file_name_parts[-1] eq $answer_file_parts[-1])) {
 2206:                         # gets here if filename and extension match, regardless of version
 2207:                         if (scalar @file_name_parts == 3) { # a versioned file is found
 2208:                             # so save it for later
 2209:                             if ($file_name_parts[1] > $version) {$version = $file_name_parts[1]};
 2210:                         }
 2211:                     }
 2212:                 }
 2213:                 $version++;
 2214:                 my $home_server = &Apache::lonnet::homeserver($stuname,$domain,undef);
 2215:                 $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stuname/$directory$answer_file");
 2216:                 # $env{'form.copy.filename'}='';
 2217:                 my $copy_result = &Apache::lonnet::finishuserfileupload($stuname,$domain,$home_server,'copy',
 2218:                                     '/portfolio'.$directory.$answer_file_parts[0].'.'.$version.'.'.$answer_file_parts[-1]);
 2219:                 &Apache::lonnet::logthis('copy result is '.$copy_result);
 2220:                 &Apache::lonnet::logthis('answer file is '.$answer_file.
 2221:                         ' becomes '.$answer_file_parts[0].'.'.$version.'.'.$answer_file_parts[-1]);
 2222:                 &Apache::lonnet::logthis('from dir list is '.$file_names[0].' has '.@file_name_parts.' parts');
 2223:             }
 2224:             &Apache::lonnet::logthis('found key portfiles '.$key);
 2225:             &Apache::lonnet::logthis('found value portfiles '.$$record{$key});
 2226:         }
 2227:     } 
 2228:     
 2229:     
 2230: }
 2231: 
 2232: #--------------------------------------------------------------------------------------
 2233: #
 2234: #-------------------------- Next few routines handles grading by section or whole class
 2235: #
 2236: #--- Javascript to handle grading by section or whole class
 2237: sub viewgrades_js {
 2238:     my ($request) = shift;
 2239: 
 2240:     $request->print(<<VIEWJAVASCRIPT);
 2241: <script type="text/javascript" language="javascript">
 2242:    function writePoint(partid,weight,point) {
 2243: 	var radioButton = document.classgrade["RADVAL_"+partid];
 2244: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 2245: 	if (point == "textval") {
 2246: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 2247: 	    if (isNaN(point) || parseFloat(point) < 0) {
 2248: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 2249: 		var resetbox = false;
 2250: 		for (var i=0; i<radioButton.length; i++) {
 2251: 		    if (radioButton[i].checked) {
 2252: 			textbox.value = i;
 2253: 			resetbox = true;
 2254: 		    }
 2255: 		}
 2256: 		if (!resetbox) {
 2257: 		    textbox.value = "";
 2258: 		}
 2259: 		return;
 2260: 	    }
 2261: 	    if (parseFloat(point) > parseFloat(weight)) {
 2262: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 2263: 				   ") greater than the weight for the part. Accept?");
 2264: 		if (resp == false) {
 2265: 		    textbox.value = "";
 2266: 		    return;
 2267: 		}
 2268: 	    }
 2269: 	    for (var i=0; i<radioButton.length; i++) {
 2270: 		radioButton[i].checked=false;
 2271: 		if (parseFloat(point) == i) {
 2272: 		    radioButton[i].checked=true;
 2273: 		}
 2274: 	    }
 2275: 
 2276: 	} else {
 2277: 	    textbox.value = parseFloat(point);
 2278: 	}
 2279: 	for (i=0;i<document.classgrade.total.value;i++) {
 2280: 	    var user = document.classgrade["ctr"+i].value;
 2281: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 2282: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 2283: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 2284: 	    if (saveval != "correct") {
 2285: 		scorename.value = point;
 2286: 		if (selname[0].selected != true) {
 2287: 		    selname[0].selected = true;
 2288: 		}
 2289: 	    }
 2290: 	}
 2291: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 2292:     }
 2293: 
 2294:     function writeRadText(partid,weight) {
 2295: 	var selval   = document.classgrade["SELVAL_"+partid];
 2296: 	var radioButton = document.classgrade["RADVAL_"+partid];
 2297: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 2298: 	if (selval[1].selected || selval[2].selected) {
 2299: 	    for (var i=0; i<radioButton.length; i++) {
 2300: 		radioButton[i].checked=false;
 2301: 
 2302: 	    }
 2303: 	    textbox.value = "";
 2304: 
 2305: 	    for (i=0;i<document.classgrade.total.value;i++) {
 2306: 		var user = document.classgrade["ctr"+i].value;
 2307: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 2308: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 2309: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 2310: 		if (saveval != "correct") {
 2311: 		    scorename.value = "";
 2312: 		    if (selval[1].selected) {
 2313: 			selname[1].selected = true;
 2314: 		    } else {
 2315: 			selname[2].selected = true;
 2316: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 2317: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 2318: 		    }
 2319: 		}
 2320: 	    }
 2321: 	} else {
 2322: 	    for (i=0;i<document.classgrade.total.value;i++) {
 2323: 		var user = document.classgrade["ctr"+i].value;
 2324: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 2325: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 2326: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 2327: 		if (saveval != "correct") {
 2328: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 2329: 		    selname[0].selected = true;
 2330: 		}
 2331: 	    }
 2332: 	}	    
 2333:     }
 2334: 
 2335:     function changeSelect(partid,user) {
 2336: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 2337: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 2338: 	var point  = textbox.value;
 2339: 	var weight = document.classgrade["weight_"+partid].value;
 2340: 
 2341: 	if (isNaN(point) || parseFloat(point) < 0) {
 2342: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 2343: 	    textbox.value = "";
 2344: 	    return;
 2345: 	}
 2346: 	if (parseFloat(point) > parseFloat(weight)) {
 2347: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 2348: 			       ") greater than the weight of the part. Accept?");
 2349: 	    if (resp == false) {
 2350: 		textbox.value = "";
 2351: 		return;
 2352: 	    }
 2353: 	}
 2354: 	selval[0].selected = true;
 2355:     }
 2356: 
 2357:     function changeOneScore(partid,user) {
 2358: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 2359: 	if (selval[1].selected || selval[2].selected) {
 2360: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 2361: 	    if (selval[2].selected) {
 2362: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 2363: 	    }
 2364: 	}
 2365:     }
 2366: 
 2367:     function resetEntry(numpart) {
 2368: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 2369: 	    var partid = document.classgrade["partid_"+ctpart].value;
 2370: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 2371: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 2372: 	    var selval  = document.classgrade["SELVAL_"+partid];
 2373: 	    for (var i=0; i<radioButton.length; i++) {
 2374: 		radioButton[i].checked=false;
 2375: 
 2376: 	    }
 2377: 	    textbox.value = "";
 2378: 	    selval[0].selected = true;
 2379: 
 2380: 	    for (i=0;i<document.classgrade.total.value;i++) {
 2381: 		var user = document.classgrade["ctr"+i].value;
 2382: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 2383: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 2384: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 2385: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 2386: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 2387: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 2388: 		if (saveselval == "excused") {
 2389: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 2390: 		} else {
 2391: 		    if (selname[0].selected == false) {selname[0].selected = true};
 2392: 		}
 2393: 	    }
 2394: 	}
 2395:     }
 2396: 
 2397: </script>
 2398: VIEWJAVASCRIPT
 2399: }
 2400: 
 2401: #--- show scores for a section or whole class w/ option to change/update a score
 2402: sub viewgrades {
 2403:     my ($request) = shift;
 2404:     &viewgrades_js($request);
 2405: 
 2406:     my ($symb,$url) = ($env{'form.symb'},$env{'form.url'}); 
 2407:     #need to make sure we have the correct data for later EXT calls, 
 2408:     #thus invalidate the cache
 2409:     &Apache::lonnet::devalidatecourseresdata(
 2410:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 2411:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 2412:     &Apache::lonnet::clear_EXT_cache_status();
 2413: 
 2414:     my $result='<h3><font color="#339933">'.&mt('Manual Grading').'</font></h3>';
 2415:     $result.='<font size=+1><b>Current Resource: </b>'.$env{'form.probTitle'}.'</font>'."\n";
 2416: 
 2417:     #view individual student submission form - called using Javascript viewOneStudent
 2418:     $result.=&jscriptNform($url,$symb);
 2419: 
 2420:     #beginning of class grading form
 2421:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 2422: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
 2423: 	'<input type="hidden" name="url"     value="'.$url.'" />'."\n".
 2424: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 2425: 	'<input type="hidden" name="section" value="'.$env{'form.section'}.'" />'."\n".
 2426: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 2427: 	'<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
 2428: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 2429: 
 2430:     my $sectionClass;
 2431:     if ($env{'form.section'} eq 'all') {
 2432: 	$sectionClass='Class </h3>';
 2433:     } elsif ($env{'form.section'} eq 'none') {
 2434: 	$sectionClass='Students in no Section </h3>';
 2435:     } else {
 2436: 	$sectionClass='Students in Section '.$env{'form.section'}.'</h3>';
 2437:     }
 2438:     $result.='<h3>Assign Common Grade To '.$sectionClass;
 2439:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
 2440: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
 2441:     #radio buttons/text box for assigning points for a section or class.
 2442:     #handles different parts of a problem
 2443:     my ($partlist,$handgrade) = &response_type($url,$symb);
 2444:     my %weight = ();
 2445:     my $ctsparts = 0;
 2446:     $result.='<table border="0">';
 2447:     my %seen = ();
 2448:     for (sort keys(%$handgrade)) {
 2449: 	my ($partid,$respid) = split (/_/,$_,2);
 2450: 	next if $seen{$partid};
 2451: 	$seen{$partid}++;
 2452: 	my $handgrade=$$handgrade{$_};
 2453: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 2454: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 2455: 
 2456: 	$result.='<input type="hidden" name="partid_'.
 2457: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 2458: 	$result.='<input type="hidden" name="weight_'.
 2459: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 2460: 	my $display_part=&get_display_part($partid,$url,$symb);
 2461: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
 2462: 	$result.='<table border="0"><tr>';  
 2463: 	my $ctr = 0;
 2464: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 2465: 	    $result.= '<td><input type="radio" name="RADVAL_'.$partid.'" '.
 2466: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 2467: 		','.$ctr.')" />'.$ctr."</td>\n";
 2468: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 2469: 	    $ctr++;
 2470: 	}
 2471: 	$result.='</tr></table>';
 2472: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
 2473: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 2474: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 2475: 	    $weight{$partid}.' (problem weight)</td>'."\n";
 2476: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
 2477: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 2478: 		$weight{$partid}.')"> '.
 2479: 	    '<option selected="on"> </option>'.
 2480: 	    '<option>excused</option>'.
 2481: 	    '<option>reset status</option></select></td></tr>'."\n";
 2482: 	$ctsparts++;
 2483:     }
 2484:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
 2485: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 2486:     $result.='<input type="button" value="Reset" '.
 2487: 	'onClick="javascript:resetEntry('.$ctsparts.');" TARGET=_self>';
 2488: 
 2489:     #table listing all the students in a section/class
 2490:     #header of table
 2491:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
 2492:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
 2493: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
 2494: 	'<td>'.&nameUserString('header')."</td>\n";
 2495:     my (@parts) = sort(&getpartlist($url,$symb));
 2496:     foreach my $part (@parts) {
 2497: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 2498: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
 2499: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 2500: 	my ($partid) = &split_part_type($part);
 2501: 	my $display_part=&get_display_part($partid,$url,$symb);
 2502: 	if ($display =~ /^Partial Credit Factor/) {
 2503: 	    $result.='<td><b>Score Part:</b> '.$display_part.
 2504: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
 2505: 	    next;
 2506: 	} else {
 2507: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
 2508: 	}
 2509: 	$display =~ s|Problem Status|Grade Status<br />|;
 2510: 	$result.='<td><b>'.$display.'</td>'."\n";
 2511:     }
 2512:     $result.='</tr>';
 2513: 
 2514:     #get info for each student
 2515:     #list all the students - with points and grade status
 2516:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2517:     my $ctr = 0;
 2518:     foreach (sort {lc($$fullname{$a}) cmp lc($$fullname{$b}) } keys %$fullname) {
 2519: 	$ctr++;
 2520: 	$result.=&viewstudentgrade($url,$symb,$env{'request.course.id'},
 2521: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr);
 2522:     }
 2523:     $result.='</table></td></tr></table>';
 2524:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 2525:     $result.='<input type="button" value="Save" '.
 2526: 	'onClick="javascript:submit();" TARGET=_self /></form>'."\n";
 2527:     if (scalar(%$fullname) eq 0) {
 2528: 	my $colspan=3+scalar(@parts);
 2529: 	$result='<font color="red">There are no students in section "'.$env{'form.section'}.
 2530: 	    '" with enrollment status "'.$env{'form.Status'}.'" to modify or grade.</font>';
 2531:     }
 2532:     $result.=&show_grading_menu_form($symb,$url);
 2533:     return $result;
 2534: }
 2535: 
 2536: #--- call by previous routine to display each student
 2537: sub viewstudentgrade {
 2538:     my ($url,$symb,$courseid,$student,$fullname,$parts,$weight,$ctr) = @_;
 2539:     my ($uname,$udom) = split(/:/,$student);
 2540:     $student=~s/:/_/;
 2541:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 2542:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
 2543: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 2544: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 2545: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 2546: 	'\')"; TARGET=_self>'.$fullname.'</a> '.
 2547: 	'<font color="#999999">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</font></td>'."\n";
 2548:     foreach my $apart (@$parts) {
 2549: 	my ($part,$type) = &split_part_type($apart);
 2550: 	my $score=$record{"resource.$part.$type"};
 2551: 	$result.='<td align="middle">';
 2552: 	if ($type eq 'awarded') {
 2553: 	    my $pts = $score eq '' ? '' : $score*$$weight{$part};
 2554: 	    $result.='<input type="hidden" name="'.
 2555: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 2556: 	    $result.='<input type="text" name="'.
 2557: 		'GD_'.$student.'_'.$part.'_awarded" '.
 2558: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 2559: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 2560: 	} elsif ($type eq 'solved') {
 2561: 	    my ($status,$foo)=split(/_/,$score,2);
 2562: 	    $status = 'nothing' if ($status eq '');
 2563: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 2564: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 2565: 	    $result.='&nbsp;<select name="'.
 2566: 		'GD_'.$student.'_'.$part.'_solved" '.
 2567: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 2568: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="on">excused</option>' 
 2569: 		: '<option selected="on"> </option><option>excused</option>')."\n";
 2570: 	    $result.='<option>reset status</option>';
 2571: 	    $result.="</select>&nbsp;</td>\n";
 2572: 	} else {
 2573: 	    $result.='<input type="hidden" name="'.
 2574: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 2575: 		    "\n";
 2576: 	    $result.='<input type="text" name="'.
 2577: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 2578: 		'value="'.$score.'" size="4" /></td>'."\n";
 2579: 	}
 2580:     }
 2581:     $result.='</tr>';
 2582:     return $result;
 2583: }
 2584: 
 2585: #--- change scores for all the students in a section/class
 2586: #    record does not get update if unchanged
 2587: sub editgrades {
 2588:     my ($request) = @_;
 2589: 
 2590:     my $symb=$env{'form.symb'};
 2591:     my $url =$env{'form.url'};
 2592:     my $title='<h3><font color="#339933">Current Grade Status</font></h3>';
 2593:     $title.='<font size=+1><b>Current Resource: </b>'.$env{'form.probTitle'}.'</font><br />'."\n";
 2594:     $title.='<font size=+1><b>Section: </b>'.$env{'form.section'}.'</font>'."\n";
 2595: 
 2596:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
 2597:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
 2598: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
 2599: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
 2600: 
 2601:     my %scoreptr = (
 2602: 		    'correct'  =>'correct_by_override',
 2603: 		    'incorrect'=>'incorrect_by_override',
 2604: 		    'excused'  =>'excused',
 2605: 		    'ungraded' =>'ungraded_attempted',
 2606: 		    'nothing'  => '',
 2607: 		    );
 2608:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 2609: 
 2610:     my (@partid);
 2611:     my %weight = ();
 2612:     my %columns = ();
 2613:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 2614: 
 2615:     my (@parts) = sort(&getpartlist($url,$symb));
 2616:     my $header;
 2617:     while ($ctr < $env{'form.totalparts'}) {
 2618: 	my $partid = $env{'form.partid_'.$ctr};
 2619: 	push @partid,$partid;
 2620: 	$weight{$partid} = $env{'form.weight_'.$partid};
 2621: 	$ctr++;
 2622:     }
 2623:     foreach my $partid (@partid) {
 2624: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
 2625: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
 2626: 	$columns{$partid}=2;
 2627: 	foreach my $stores (@parts) {
 2628: 	    my ($part,$type) = &split_part_type($stores);
 2629: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 2630: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 2631: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 2632: 	    $display =~ s/\[Part: (\w)+\]//;
 2633: 	    $display =~ s/Number of Attempts/Tries/;
 2634: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
 2635: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
 2636: 	    $columns{$partid}+=2;
 2637: 	}
 2638:     }
 2639:     foreach my $partid (@partid) {
 2640: 	my $display_part=&get_display_part($partid,$url,$symb);
 2641: 	$result .= '<td colspan="'.$columns{$partid}.
 2642: 	    '" align="center"><b>Part:</b> '.$display_part.
 2643: 	    ' (Weight = '.$weight{$partid}.')</td>';
 2644: 
 2645:     }
 2646:     $result .= '</tr><tr bgcolor="#deffff">';
 2647:     $result .= $header;
 2648:     $result .= '</tr>'."\n";
 2649:     my $noupdate;
 2650:     my ($updateCtr,$noupdateCtr) = (1,1);
 2651:     for ($i=0; $i<$env{'form.total'}; $i++) {
 2652: 	my $line;
 2653: 	my $user = $env{'form.ctr'.$i};
 2654: 	my $usercolon = $user;
 2655: 	$usercolon =~s/_/:/;
 2656: 	my ($uname,$udom)=split(/_/,$user);
 2657: 	my %newrecord;
 2658: 	my $updateflag = 0;
 2659: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$usercolon},$uname,$udom).'</td>';
 2660: 	my $usec=$classlist->{"$uname:$udom"}[5];
 2661: 	if (!&canmodify($usec)) {
 2662: 	    my $numcols=scalar(@partid)*4+2;
 2663: 	    $noupdate.=$line."<td colspan=\"$numcols\"><font color=\"red\">Not allowed to modify student</font></td></tr>";
 2664: 	    next;
 2665: 	}
 2666: 	foreach (@partid) {
 2667: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 2668: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 2669: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 2670: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 2671: 
 2672: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 2673: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 2674: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 2675: 	    my $score;
 2676: 	    if ($partial eq '') {
 2677: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 2678: 	    } elsif ($partial > 0) {
 2679: 		$score = 'correct_by_override';
 2680: 	    } elsif ($partial == 0) {
 2681: 		$score = 'incorrect_by_override';
 2682: 	    }
 2683: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 2684: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 2685: 
 2686: 	    if ($dropMenu eq 'reset status' &&
 2687: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 2688: 		$newrecord{'resource.'.$_.'.tries'} = 0;
 2689: 		$newrecord{'resource.'.$_.'.solved'} = '';
 2690: 		$newrecord{'resource.'.$_.'.award'} = '';
 2691: 		$newrecord{'resource.'.$_.'.awarded'} = 0;
 2692: 		$newrecord{'resource.'.$_.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2693: 		$updateflag = 1;
 2694: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 2695: 		$updateflag = 1;
 2696: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 2697: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 2698: 		$rec_update++;
 2699: 	    }
 2700: 
 2701: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 2702: 		'<td align="center">'.$awarded.
 2703: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 2704: 
 2705: 
 2706: 	    my $partid=$_;
 2707: 	    foreach my $stores (@parts) {
 2708: 		my ($part,$type) = &split_part_type($stores);
 2709: 		if ($part !~ m/^\Q$partid\E/) { next;}
 2710: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 2711: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 2712: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 2713: 		if ($awarded ne '' && $awarded ne $old_aw) {
 2714: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 2715: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2716: 		    $updateflag=1;
 2717: 		}
 2718: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 2719: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 2720: 	    }
 2721: 	}
 2722: 	$line.='</tr>'."\n";
 2723: 	if ($updateflag) {
 2724: 	    $count++;
 2725: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 2726: 				    $udom,$uname);
 2727: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
 2728: 	    $updateCtr++;
 2729: 	} else {
 2730: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
 2731: 	    $noupdateCtr++;
 2732: 	}
 2733:     }
 2734:     if ($noupdate) {
 2735: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 2736: 	my $numcols=scalar(@partid)*4+2;
 2737: 	$result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr><tr bgcolor="#ffffde">'.$noupdate;
 2738:     }
 2739:     $result .= '</table></td></tr></table>'."\n".
 2740: 	&show_grading_menu_form ($symb,$url);
 2741:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
 2742: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
 2743: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
 2744:     return $title.$msg.$result;
 2745: }
 2746: 
 2747: sub split_part_type {
 2748:     my ($partstr) = @_;
 2749:     my ($temp,@allparts)=split(/_/,$partstr);
 2750:     my $type=pop(@allparts);
 2751:     my $part=join('.',@allparts);
 2752:     return ($part,$type);
 2753: }
 2754: 
 2755: #------------- end of section for handling grading by section/class ---------
 2756: #
 2757: #----------------------------------------------------------------------------
 2758: 
 2759: 
 2760: #----------------------------------------------------------------------------
 2761: #
 2762: #-------------------------- Next few routines handles grading by csv upload
 2763: #
 2764: #--- Javascript to handle csv upload
 2765: sub csvupload_javascript_reverse_associate {
 2766:     my $error1=&mt('You need to specify the username or ID');
 2767:     my $error2=&mt('You need to specify at least one grading field');
 2768:   return(<<ENDPICK);
 2769:   function verify(vf) {
 2770:     var foundsomething=0;
 2771:     var founduname=0;
 2772:     var foundID=0;
 2773:     for (i=0;i<=vf.nfields.value;i++) {
 2774:       tw=eval('vf.f'+i+'.selectedIndex');
 2775:       if (i==0 && tw!=0) { foundID=1; }
 2776:       if (i==1 && tw!=0) { founduname=1; }
 2777:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 2778:     }
 2779:     if (founduname==0 && foundID==0) {
 2780: 	alert('$error1');
 2781: 	return;
 2782:     }
 2783:     if (foundsomething==0) {
 2784: 	alert('$error2');
 2785: 	return;
 2786:     }
 2787:     vf.submit();
 2788:   }
 2789:   function flip(vf,tf) {
 2790:     var nw=eval('vf.f'+tf+'.selectedIndex');
 2791:     var i;
 2792:     for (i=0;i<=vf.nfields.value;i++) {
 2793:       //can not pick the same destination field for both name and domain
 2794:       if (((i ==0)||(i ==1)) && 
 2795:           ((tf==0)||(tf==1)) && 
 2796:           (i!=tf) &&
 2797:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 2798:         eval('vf.f'+i+'.selectedIndex=0;')
 2799:       }
 2800:     }
 2801:   }
 2802: ENDPICK
 2803: }
 2804: 
 2805: sub csvupload_javascript_forward_associate {
 2806:     my $error1=&mt('You need to specify the username or ID');
 2807:     my $error2=&mt('You need to specify at least one grading field');
 2808:   return(<<ENDPICK);
 2809:   function verify(vf) {
 2810:     var foundsomething=0;
 2811:     var founduname=0;
 2812:     var foundID=0;
 2813:     for (i=0;i<=vf.nfields.value;i++) {
 2814:       tw=eval('vf.f'+i+'.selectedIndex');
 2815:       if (tw==1) { foundID=1; }
 2816:       if (tw==2) { founduname=1; }
 2817:       if (tw>3) { foundsomething=1; }
 2818:     }
 2819:     if (founduname==0 && foundID==0) {
 2820: 	alert('$error1');
 2821: 	return;
 2822:     }
 2823:     if (foundsomething==0) {
 2824: 	alert('$error2');
 2825: 	return;
 2826:     }
 2827:     vf.submit();
 2828:   }
 2829:   function flip(vf,tf) {
 2830:     var nw=eval('vf.f'+tf+'.selectedIndex');
 2831:     var i;
 2832:     //can not pick the same destination field twice
 2833:     for (i=0;i<=vf.nfields.value;i++) {
 2834:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 2835:         eval('vf.f'+i+'.selectedIndex=0;')
 2836:       }
 2837:     }
 2838:   }
 2839: ENDPICK
 2840: }
 2841: 
 2842: sub csvuploadmap_header {
 2843:     my ($request,$symb,$url,$datatoken,$distotal)= @_;
 2844:     my $javascript;
 2845:     if ($env{'form.upfile_associate'} eq 'reverse') {
 2846: 	$javascript=&csvupload_javascript_reverse_associate();
 2847:     } else {
 2848: 	$javascript=&csvupload_javascript_forward_associate();
 2849:     }
 2850: 
 2851:     my ($result) = &showResourceInfo($url,$env{'form.probTitle'});
 2852:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 2853:     my $ignore=&mt('Ignore First Line');
 2854:     $request->print(<<ENDPICK);
 2855: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 2856: <h3><font color="#339933">Uploading Class Grades</font></h3>
 2857: $result
 2858: <hr>
 2859: <h3>Identify fields</h3>
 2860: Total number of records found in file: $distotal <hr />
 2861: Enter as many fields as you can. The system will inform you and bring you back
 2862: to this page if the data selected is insufficient to run your class.<hr />
 2863: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 2864: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 2865: <input type="hidden" name="associate"  value="" />
 2866: <input type="hidden" name="phase"      value="three" />
 2867: <input type="hidden" name="datatoken"  value="$datatoken" />
 2868: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 2869: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 2870: <input type="hidden" name="upfile_associate" 
 2871:                                        value="$env{'form.upfile_associate'}" />
 2872: <input type="hidden" name="symb"       value="$symb" />
 2873: <input type="hidden" name="url"        value="$url" />
 2874: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 2875: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 2876: <input type="hidden" name="command"    value="csvuploadoptions" />
 2877: <hr />
 2878: <script type="text/javascript" language="Javascript">
 2879: $javascript
 2880: </script>
 2881: ENDPICK
 2882:     return '';
 2883: 
 2884: }
 2885: 
 2886: sub csvupload_fields {
 2887:     my ($url,$symb) = @_;
 2888:     my (@parts) = &getpartlist($url,$symb);
 2889:     my @fields=(['ID','Student ID'],
 2890: 		['username','Student Username'],
 2891: 		['domain','Student Domain']);
 2892:     foreach my $part (sort(@parts)) {
 2893: 	my @datum;
 2894: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 2895: 	my $name=$part;
 2896: 	if  (!$display) { $display = $name; }
 2897: 	@datum=($name,$display);
 2898: 	if ($name=~/^stores_(.*)_awarded/) {
 2899: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 2900: 	}
 2901: 	push(@fields,\@datum);
 2902:     }
 2903:     return (@fields);
 2904: }
 2905: 
 2906: sub csvuploadmap_footer {
 2907:     my ($request,$i,$keyfields) =@_;
 2908:     $request->print(<<ENDPICK);
 2909: </table>
 2910: <input type="hidden" name="nfields" value="$i" />
 2911: <input type="hidden" name="keyfields" value="$keyfields" />
 2912: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 2913: </form>
 2914: ENDPICK
 2915: }
 2916: 
 2917: sub upcsvScores_form {
 2918:     my ($request) = shift;
 2919:     my ($symb,$url)=&get_symb_and_url($request);
 2920:     if (!$symb) {return '';}
 2921:     my $result =<<CSVFORMJS;
 2922: <script type="text/javascript" language="javascript">
 2923:     function checkUpload(formname) {
 2924: 	if (formname.upfile.value == "") {
 2925: 	    alert("Please use the browse button to select a file from your local directory.");
 2926: 	    return false;
 2927: 	}
 2928: 	formname.submit();
 2929:     }
 2930:     </script>
 2931: CSVFORMJS
 2932:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 2933:     my ($table) = &showResourceInfo($url,$env{'form.probTitle'});
 2934:     $result.=$table;
 2935:     $result.='<br /><table width=100% border=0><tr><td bgcolor="#777777">'."\n";
 2936:     $result.='<table width=100% border=0><tr bgcolor="#e6ffff"><td>'."\n";
 2937:     $result.='&nbsp;<b>Specify a file containing the class scores for current resource'.
 2938: 	'.</b></td></tr>'."\n";
 2939:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 2940:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 2941:     my $ignore=&mt('Ignore First Line');
 2942:     $result.=<<ENDUPFORM;
 2943: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 2944: <input type="hidden" name="symb" value="$symb" />
 2945: <input type="hidden" name="url" value="$url" />
 2946: <input type="hidden" name="command" value="csvuploadmap" />
 2947: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 2948: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 2949: $upfile_select
 2950: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scores" />
 2951: <label><input type="checkbox" name="noFirstLine" />$ignore</lable>
 2952: </form>
 2953: ENDUPFORM
 2954:     $result.='</td></tr></table>'."\n";
 2955:     $result.='</td></tr></table><br /><br />'."\n";
 2956:     $result.=&show_grading_menu_form($symb,$url);
 2957:     return $result;
 2958: }
 2959: 
 2960: 
 2961: sub csvuploadmap {
 2962:     my ($request)= @_;
 2963:     my ($symb,$url)=&get_symb_and_url($request);
 2964:     if (!$symb) {return '';}
 2965: 
 2966:     my $datatoken;
 2967:     if (!$env{'form.datatoken'}) {
 2968: 	$datatoken=&Apache::loncommon::upfile_store($request);
 2969:     } else {
 2970: 	$datatoken=$env{'form.datatoken'};
 2971: 	&Apache::loncommon::load_tmp_file($request);
 2972:     }
 2973:     my @records=&Apache::loncommon::upfile_record_sep();
 2974:     if ($env{'form.noFirstLine'}) { shift(@records); }
 2975:     &csvuploadmap_header($request,$symb,$url,$datatoken,$#records+1);
 2976:     my ($i,$keyfields);
 2977:     if (@records) {
 2978: 	my @fields=&csvupload_fields($url,$symb);
 2979: 
 2980: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 2981: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 2982: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 2983: 							  \@fields);
 2984: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 2985: 	    chop($keyfields);
 2986: 	} else {
 2987: 	    unshift(@fields,['none','']);
 2988: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 2989: 							    \@fields);
 2990: 	    my %sone=&Apache::loncommon::record_sep($records[0]);
 2991: 	    $keyfields=join(',',sort(keys(%sone)));
 2992: 	}
 2993:     }
 2994:     &csvuploadmap_footer($request,$i,$keyfields);
 2995:     $request->print(&show_grading_menu_form($symb,$url));
 2996: 
 2997:     return '';
 2998: }
 2999: 
 3000: sub csvuploadoptions {
 3001:     my ($request)= @_;
 3002:     my ($symb,$url)=&get_symb_and_url($request);
 3003:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3004:     my $ignore=&mt('Ignore First Line');
 3005:     $request->print(<<ENDPICK);
 3006: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3007: <h3><font color="#339933">Uploading Class Grade Options</font></h3>
 3008: <input type="hidden" name="command"    value="csvuploadassign" />
 3009: <input type="submit" value="Assign Grades" /><br />
 3010: <p>
 3011: <label>
 3012:    <input type="checkbox" name="show_full_results" />
 3013:    Show a table of all changes
 3014: </label>
 3015: </p>
 3016: <p>
 3017: <label>
 3018:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3019:    Overwrite any existing score
 3020: </label>
 3021: </p>
 3022: ENDPICK
 3023:     my %fields=&get_fields();
 3024:     if (!defined($fields{'domain'})) {
 3025: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3026: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3027:     }
 3028:     foreach my $key (sort(keys(%env))) {
 3029: 	if ($key !~ /^form\.(.*)$/) { next; }
 3030: 	my $cleankey=$1;
 3031: 	if ($cleankey eq 'command') { next; }
 3032: 	$request->print('<input type="hidden" name="'.$cleankey.
 3033: 			'"  value="'.$env{$key}.'" />'."\n");
 3034:     }
 3035:     # FIXME do a check for any duplicated user ids...
 3036:     # FIXME do a check for any invalid user ids?...
 3037:     $request->print("<hr /></form>\n");
 3038:     $request->print(&show_grading_menu_form($symb,$url));
 3039:     return '';
 3040: }
 3041: 
 3042: sub get_fields {
 3043:     my %fields;
 3044:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3045:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3046: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3047: 	    if ($env{'form.f'.$i} ne 'none') {
 3048: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3049: 	    }
 3050: 	} else {
 3051: 	    if ($env{'form.f'.$i} ne 'none') {
 3052: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3053: 	    }
 3054: 	}
 3055:     }
 3056:     return %fields;
 3057: }
 3058: 
 3059: sub csvuploadassign {
 3060:     my ($request)= @_;
 3061:     my ($symb,$url)=&get_symb_and_url($request);
 3062:     if (!$symb) {return '';}
 3063:     &Apache::loncommon::load_tmp_file($request);
 3064:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 3065:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 3066:     my %fields=&get_fields();
 3067:     $request->print('<h3>Assigning Grades</h3>');
 3068:     my $courseid=$env{'request.course.id'};
 3069:     my ($classlist) = &getclasslist('all',0);
 3070:     my @notallowed;
 3071:     my @skipped;
 3072:     my $countdone=0;
 3073:     foreach my $grade (@gradedata) {
 3074: 	my %entries=&Apache::loncommon::record_sep($grade);
 3075: 	my $domain;
 3076: 	if ($entries{$fields{'domain'}}) {
 3077: 	    $domain=$entries{$fields{'domain'}};
 3078: 	} else {
 3079: 	    $domain=$env{'form.default_domain'};
 3080: 	}
 3081: 	$domain=~s/\s//g;
 3082: 	my $username=$entries{$fields{'username'}};
 3083: 	$username=~s/\s//g;
 3084: 	if (!$username) {
 3085: 	    my $id=$entries{$fields{'ID'}};
 3086: 	    $id=~s/\s//g;
 3087: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 3088: 	    $username=$ids{$id};
 3089: 	}
 3090: 	if (!exists($$classlist{"$username:$domain"})) {
 3091: 	    my $id=$entries{$fields{'ID'}};
 3092: 	    $id=~s/\s//g;
 3093: 	    if ($id) {
 3094: 		push(@skipped,"$id:$domain");
 3095: 	    } else {
 3096: 		push(@skipped,"$username:$domain");
 3097: 	    }
 3098: 	    next;
 3099: 	}
 3100: 	my $usec=$classlist->{"$username:$domain"}[5];
 3101: 	if (!&canmodify($usec)) {
 3102: 	    push(@notallowed,"$username:$domain");
 3103: 	    next;
 3104: 	}
 3105: 	my %points;
 3106: 	my %grades;
 3107: 	foreach my $dest (keys(%fields)) {
 3108: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 3109: 		$dest eq 'domain') { next; }
 3110: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 3111: 	    if ($dest=~/stores_(.*)_points/) {
 3112: 		my $part=$1;
 3113: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 3114: 					      $symb,$domain,$username);
 3115: 		$entries{$fields{$dest}}=~s/\s//g;
 3116: 		my $pcr=$entries{$fields{$dest}} / $wgt;
 3117: 		my $award='correct_by_override';
 3118: 		$grades{"resource.$part.awarded"}=$pcr;
 3119: 		$grades{"resource.$part.solved"}=$award;
 3120: 		$points{$part}=1;
 3121: 	    } else {
 3122: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 3123: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 3124: 		my $store_key=$dest;
 3125: 		$store_key=~s/^stores/resource/;
 3126: 		$store_key=~s/_/\./g;
 3127: 		$grades{$store_key}=$entries{$fields{$dest}};
 3128: 	    }
 3129: 	}
 3130: 	if (! %grades) { push(@skipped,"$username:$domain no data to store"); }
 3131: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 3132: #	&Apache::lonnet::logthis(" storing ".(join('-',%grades)));
 3133: 	&Apache::lonnet::cstore(\%grades,$symb,$env{'request.course.id'},
 3134: 				$domain,$username);
 3135: 	$request->print('.');
 3136: 	$request->rflush();
 3137: 	$countdone++;
 3138:     }
 3139:     $request->print("<br />Stored $countdone students\n");
 3140:     if (@skipped) {
 3141: 	$request->print('<p<font size="+1"><b>Skipped Students</b></font></p>');
 3142: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 3143:     }
 3144:     if (@notallowed) {
 3145: 	$request->print('<p><font size="+1" color="red"><b>Students Not Allowed to Modify</b></font></p>');
 3146: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 3147:     }
 3148:     $request->print("<br />\n");
 3149:     $request->print(&show_grading_menu_form($symb,$url));
 3150:     return '';
 3151: }
 3152: #------------- end of section for handling csv file upload ---------
 3153: #
 3154: #-------------------------------------------------------------------
 3155: #
 3156: #-------------- Next few routines handle grading by page/sequence
 3157: #
 3158: #--- Select a page/sequence and a student to grade
 3159: sub pickStudentPage {
 3160:     my ($request) = shift;
 3161: 
 3162:     $request->print(<<LISTJAVASCRIPT);
 3163: <script type="text/javascript" language="javascript">
 3164: 
 3165: function checkPickOne(formname) {
 3166:     if (radioSelection(formname.student) == null) {
 3167: 	alert("Please select the student you wish to grade.");
 3168: 	return;
 3169:     }
 3170:     ptr = pullDownSelection(formname.selectpage);
 3171:     formname.page.value = formname["page"+ptr].value;
 3172:     formname.title.value = formname["title"+ptr].value;
 3173:     formname.submit();
 3174: }
 3175: 
 3176: </script>
 3177: LISTJAVASCRIPT
 3178:     &commonJSfunctions($request);
 3179:     my ($symb,$url) = &get_symb_and_url($request);
 3180:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 3181:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 3182:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 3183: 
 3184:     my $result='<h3><font color="#339933">&nbsp;'.
 3185: 	'Manual Grading by Page or Sequence</font></h3>';
 3186: 
 3187:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 3188:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
 3189:     my ($titles,$symbx) = &getSymbMap($request);
 3190:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 3191: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 3192: #    my $type=($curpage =~ /\.(page|sequence)/);
 3193:     my $ctr=0;
 3194:     foreach (@$titles) {
 3195: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 3196: 	$result.='<option value="'.$ctr.'" '.
 3197: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="on"' : '').
 3198: 	    '>'.$showtitle.'</option>'."\n";
 3199: 	$ctr++;
 3200:     }
 3201:     $result.= '</select>'."<br>\n";
 3202:     $ctr=0;
 3203:     foreach (@$titles) {
 3204: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 3205: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 3206: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 3207: 	$ctr++;
 3208:     }
 3209:     $result.='<input type="hidden" name="page" />'."\n".
 3210: 	'<input type="hidden" name="title" />'."\n";
 3211: 
 3212:     $result.='&nbsp;<b>View Problems Text: </b><input type="radio" name="vProb" value="no" checked="on" /> no '."\n".
 3213: 	'<input type="radio" name="vProb" value="yes" /> yes '."<br>\n";
 3214: 
 3215:     $result.='&nbsp;<b>Submission Details: </b>'.
 3216: 	'<input type="radio" name="lastSub" value="none" /> none'."\n".
 3217: 	'<input type="radio" name="lastSub" value="datesub" checked /> by dates and submissions'."\n".
 3218: 	'<input type="radio" name="lastSub" value="all" /> all details'."\n";
 3219: 
 3220:     $result.='<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
 3221: 	'<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
 3222: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 3223: 	'<input type="hidden" name="url"     value="'.$url.'" />'."\n".
 3224: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
 3225: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 3226: 
 3227:     $result.='&nbsp;<input type="button" '.
 3228: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
 3229: 
 3230:     $request->print($result);
 3231: 
 3232:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br>'.
 3233: 	'<table border="0"><tr><td bgcolor="#777777">'.
 3234: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 3235: 	'<td align="right">&nbsp;<b>No.</b></td>'.
 3236: 	'<td>'.&nameUserString('header').'</td>'.
 3237: 	'<td align="right">&nbsp;<b>No.</b></td>'.
 3238: 	'<td>'.&nameUserString('header').'</td></tr>';
 3239:  
 3240:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 3241:     my $ptr = 1;
 3242:     foreach my $student (sort {lc($$fullname{$a}) cmp lc($$fullname{$b}) } keys %$fullname) {
 3243: 	my ($uname,$udom) = split(/:/,$student);
 3244: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
 3245: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 3246: 	$studentTable.='<td>&nbsp;<input type="radio" name="student" value="'.$student.'" /> '
 3247: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."\n";
 3248: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
 3249: 	$ptr++;
 3250:     }
 3251:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;' if ($ptr%2 == 0);
 3252:     $studentTable.='</td></tr></table></td></tr></table>'."\n";
 3253:     $studentTable.='<input type="button" '.
 3254: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
 3255: 
 3256:     $studentTable.=&show_grading_menu_form($symb,$url);
 3257:     $request->print($studentTable);
 3258: 
 3259:     return '';
 3260: }
 3261: 
 3262: sub getSymbMap {
 3263:     my ($request) = @_;
 3264:     my $navmap = Apache::lonnavmaps::navmap->new();
 3265: 
 3266:     my %symbx = ();
 3267:     my @titles = ();
 3268:     my $minder = 0;
 3269: 
 3270:     # Gather every sequence that has problems.
 3271:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 3272: 					       1,0,1);
 3273:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 3274: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 3275: 	    my $title = $minder.'.'.$sequence->compTitle();
 3276: 	    push @titles, $title; # minder in case two titles are identical
 3277: 	    $symbx{$title} = $sequence->symb();
 3278: 	    $minder++;
 3279: 	}
 3280:     }
 3281:     return \@titles,\%symbx;
 3282: }
 3283: 
 3284: #
 3285: #--- Displays a page/sequence w/wo problems, w/wo submissions
 3286: sub displayPage {
 3287:     my ($request) = shift;
 3288: 
 3289:     my ($symb,$url) = &get_symb_and_url($request);
 3290:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 3291:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 3292:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 3293:     my $pageTitle = $env{'form.page'};
 3294:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 3295:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 3296:     my $usec=$classlist->{$env{'form.student'}}[5];
 3297: 
 3298:     #need to make sure we have the correct data for later EXT calls, 
 3299:     #thus invalidate the cache
 3300:     &Apache::lonnet::devalidatecourseresdata(
 3301:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3302:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3303:     &Apache::lonnet::clear_EXT_cache_status();
 3304: 
 3305:     if (!&canview($usec)) {
 3306: 	$request->print('<font color="red">Unable to view requested student.('.$env{'form.student'}.')</font>');
 3307: 	$request->print(&show_grading_menu_form($symb,$url));
 3308: 	return;
 3309:     }
 3310:     my $result='<h3><font color="#339933">&nbsp;'.$env{'form.title'}.'</font></h3>';
 3311:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
 3312: 	'</h3>'."\n";
 3313:     &sub_page_js($request);
 3314:     $request->print($result);
 3315: 
 3316:     my $navmap = Apache::lonnavmaps::navmap->new();
 3317:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 3318:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 3319: 
 3320:     my $iterator = $navmap->getIterator($map->map_start(),
 3321: 					$map->map_finish());
 3322: 
 3323:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 3324: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 3325: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 3326: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 3327: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 3328: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 3329: 	'<input type="hidden" name="url"     value="'.$url.'" />'."\n".
 3330: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
 3331: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 3332: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 3333: 
 3334:     my $checkIcon = '<img src="'.$request->dir_config('lonIconsURL').
 3335: 	'/check.gif" height="16" border="0" />';
 3336: 
 3337:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
 3338: 	' symbol.'."\n".
 3339: 	'<table border="0"><tr><td bgcolor="#777777">'.
 3340: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 3341: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
 3342: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
 3343: 
 3344:     my ($depth,$question,$prob) = (1,1,1);
 3345:     $iterator->next(); # skip the first BEGIN_MAP
 3346:     my $curRes = $iterator->next(); # for "current resource"
 3347:     while ($depth > 0) {
 3348:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 3349:         if($curRes == $iterator->END_MAP) { $depth--; }
 3350: 
 3351:         if (ref($curRes) && $curRes->is_problem() && !$curRes->randomout) {
 3352: 	    my $parts = $curRes->parts();
 3353:             my $title = $curRes->compTitle();
 3354: 	    my $symbx = $curRes->symb();
 3355: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
 3356: 		(scalar(@{$parts}) == 1 ? '' : '<br>('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
 3357: 	    $studentTable.='<td valign="top">';
 3358: 	    if ($env{'form.vProb'} eq 'yes' ) {
 3359: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 3360: 					     undef,'both');
 3361: 	    } else {
 3362: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'});
 3363: 		$companswer =~ s|<form(.*?)>||g;
 3364: 		$companswer =~ s|</form>||g;
 3365: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 3366: #		    $companswer =~ s/$1/ /ms;
 3367: #		    $request->print('match='.$1."<br>\n");
 3368: #		}
 3369: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 3370: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br>&nbsp;<b>Correct answer:</b><br>'.$companswer;
 3371: 	    }
 3372: 
 3373: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 3374: 
 3375: 	    if ($env{'form.lastSub'} eq 'datesub') {
 3376: 		if ($record{'version'} eq '') {
 3377: 		    $studentTable.='<br />&nbsp;<font color="red">No recorded submission for this problem</font><br />';
 3378: 		} else {
 3379: 		    my %responseType = ();
 3380: 		    foreach my $partid (@{$parts}) {
 3381: 			my @responseIds =$curRes->responseIds($partid);
 3382: 			my @responseType =$curRes->responseType($partid);
 3383: 			my %responseIds;
 3384: 			for (my $i=0;$i<=$#responseIds;$i++) {
 3385: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 3386: 			}
 3387: 			$responseType{$partid} = \%responseIds;
 3388: 		    }
 3389: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 3390: 
 3391: 		}
 3392: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 3393: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 3394: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 3395: 									$env{'request.course.id'},
 3396: 									'','.submission');
 3397:  
 3398: 	    }
 3399: 	    if (&canmodify($usec)) {
 3400: 		foreach my $partid (@{$parts}) {
 3401: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 3402: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 3403: 		    $question++;
 3404: 		}
 3405: 		$prob++;
 3406: 	    }
 3407: 	    $studentTable.='</td></tr>';
 3408: 
 3409: 	}
 3410:         $curRes = $iterator->next();
 3411:     }
 3412: 
 3413:     $studentTable.='</td></tr></table></td></tr></table>'."\n".
 3414: 	'<input type="button" value="Save" '.
 3415: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" TARGET=_self />'.
 3416: 	'</form>'."\n";
 3417:     $studentTable.=&show_grading_menu_form($symb,$url);
 3418:     $request->print($studentTable);
 3419: 
 3420:     return '';
 3421: }
 3422: 
 3423: sub displaySubByDates {
 3424:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 3425:     my $isCODE=0;
 3426:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 3427:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
 3428: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
 3429: 	'<td><b>Date/Time</b></td>'.
 3430: 	($isCODE?'<td><b>CODE</b></td>':'').
 3431: 	'<td><b>Submission</b></td>'.
 3432: 	'<td><b>Status&nbsp;</b></td></tr>';
 3433:     my ($version);
 3434:     my %mark;
 3435:     my %orders;
 3436:     $mark{'correct_by_student'} = $checkIcon;
 3437:     if (!exists($$record{'1:timestamp'})) {
 3438: 	return '<br />&nbsp;<font color="red">Nothing submitted - no attempts</font><br />';
 3439:     }
 3440:     for ($version=1;$version<=$$record{'version'};$version++) {
 3441: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
 3442: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
 3443: 	if ($isCODE) {
 3444: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 3445: 	}
 3446: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 3447: 	my @displaySub = ();
 3448: 	foreach my $partid (@{$parts}) {
 3449: 	    my @matchKey = sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys);
 3450: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 3451: 	    my $display_part=&get_display_part($partid,undef,$symb);
 3452: 	    foreach my $matchKey (@matchKey) {
 3453: 		if (exists($$record{$version.':'.$matchKey}) &&
 3454: 		    $$record{$version.':'.$matchKey} ne '') {
 3455: 		    my ($responseId)=($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/);
 3456: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
 3457: 		    $displaySub[0].='<font color="#999999">(ID&nbsp;'.
 3458: 			$responseId.')</font>&nbsp;<b>';
 3459: 		    if ($$record{"$version:resource.$partid.tries"} eq '') {
 3460: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
 3461: 		    } else {
 3462: 			$displaySub[0].='Trial&nbsp;'.
 3463: 			    $$record{"$version:resource.$partid.tries"};
 3464: 		    }
 3465: 		    my $responseType=$responseType->{$partid}->{$responseId};
 3466: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 3467: 		    if (!exists($orders{$partid}->{$responseId})) {
 3468: 			$orders{$partid}->{$responseId}=
 3469: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
 3470: 		    }
 3471: 		    $displaySub[0].='</b>&nbsp; '.
 3472: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:").'<br />';
 3473: 		}
 3474: 	    }
 3475: 	    if (exists $$record{"$version:resource.$partid.award"}) {
 3476: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
 3477: 		    lc($$record{"$version:resource.$partid.award"}).' '.
 3478: 		    $mark{$$record{"$version:resource.$partid.solved"}}.
 3479: 		    '<br />';
 3480: 	    }
 3481: 	    if (exists $$record{"$version:resource.$partid.regrader"}) {
 3482: 		$displaySub[2].=$$record{"$version:resource.$partid.regrader"}.
 3483: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 3484: 	    }
 3485: 	}
 3486: 	# needed because old essay regrader has not parts info
 3487: 	if (exists $$record{"$version:resource.regrader"}) {
 3488: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 3489: 	}
 3490: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 3491: 	if ($displaySub[2]) {
 3492: 	    $studentTable.='Manually graded by '.$displaySub[2];
 3493: 	}
 3494: 	$studentTable.='&nbsp;</td></tr>';
 3495:     
 3496:     }
 3497:     $studentTable.='</table></td></tr></table>';
 3498:     return $studentTable;
 3499: }
 3500: 
 3501: sub updateGradeByPage {
 3502:     my ($request) = shift;
 3503: 
 3504:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 3505:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 3506:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 3507:     my $pageTitle = $env{'form.page'};
 3508:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 3509:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 3510:     my $usec=$classlist->{$env{'form.student'}}[5];
 3511:     if (!&canmodify($usec)) {
 3512: 	$request->print('<font color="red">Unable to modify requested student.('.$env{'form.student'}.'</font>');
 3513: 	$request->print(&show_grading_menu_form($env{'form.symb'},$env{'form.url'}));
 3514: 	return;
 3515:     }
 3516:     my $result='<h3><font color="#339933">&nbsp;'.$env{'form.title'}.'</font></h3>';
 3517:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 3518: 	'</h3>'."\n";
 3519: 
 3520:     $request->print($result);
 3521: 
 3522:     my $navmap = Apache::lonnavmaps::navmap->new();
 3523:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 3524:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 3525: 
 3526:     my $iterator = $navmap->getIterator($map->map_start(),
 3527: 					$map->map_finish());
 3528: 
 3529:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
 3530: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 3531: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
 3532: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
 3533: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
 3534: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
 3535: 
 3536:     $iterator->next(); # skip the first BEGIN_MAP
 3537:     my $curRes = $iterator->next(); # for "current resource"
 3538:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 3539:     while ($depth > 0) {
 3540:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 3541:         if($curRes == $iterator->END_MAP) { $depth--; }
 3542: 
 3543:         if (ref($curRes) && $curRes->is_problem() && !$curRes->randomout) {
 3544: 	    my $parts = $curRes->parts();
 3545:             my $title = $curRes->compTitle();
 3546: 	    my $symbx = $curRes->symb();
 3547: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
 3548: 		(scalar(@{$parts}) == 1 ? '' : '<br>('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
 3549: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 3550: 
 3551: 	    my %newrecord=();
 3552: 	    my @displayPts=();
 3553: 	    foreach my $partid (@{$parts}) {
 3554: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 3555: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 3556: 
 3557: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 3558: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 3559: 		my $partial = $newpts/$wgt;
 3560: 		my $score;
 3561: 		if ($partial > 0) {
 3562: 		    $score = 'correct_by_override';
 3563: 		} elsif ($newpts ne '') { #empty is taken as 0
 3564: 		    $score = 'incorrect_by_override';
 3565: 		}
 3566: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 3567: 		if ($dropMenu eq 'excused') {
 3568: 		    $partial = '';
 3569: 		    $score = 'excused';
 3570: 		} elsif ($dropMenu eq 'reset status'
 3571: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 3572: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 3573: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 3574: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 3575: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 3576: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 3577: 		    $changeflag++;
 3578: 		    $newpts = '';
 3579: 		}
 3580: 		my $display_part=&get_display_part($partid,undef,
 3581: 						   $curRes->symb());
 3582: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 3583: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
 3584: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 3585: 		    '&nbsp;<br>';
 3586: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
 3587: 		     (($score eq 'excused') ? 'excused' : $newpts).
 3588: 		    '&nbsp;<br>';
 3589: 
 3590: 		$question++;
 3591: 		next if ($dropMenu eq 'reset status' || ($newpts == $oldpts && $score ne 'excused'));
 3592: 
 3593: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 3594: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 3595: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 3596: 		    if (scalar(keys(%newrecord)) > 0);
 3597: 
 3598: 		$changeflag++;
 3599: 	    }
 3600: 	    if (scalar(keys(%newrecord)) > 0) {
 3601: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 3602: 					$udom,$uname);
 3603: 	    }
 3604: 
 3605: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 3606: 		'<td valign="top">'.$displayPts[1].'</td>'.
 3607: 		'</tr>';
 3608: 
 3609: 	    $prob++;
 3610: 	}
 3611:         $curRes = $iterator->next();
 3612:     }
 3613: 
 3614:     $studentTable.='</td></tr></table></td></tr></table>';
 3615:     $studentTable.=&show_grading_menu_form($env{'form.symb'},$env{'form.url'});
 3616:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
 3617: 		  'The scores were changed for '.
 3618: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
 3619:     $request->print($grademsg.$studentTable);
 3620: 
 3621:     return '';
 3622: }
 3623: 
 3624: #-------- end of section for handling grading by page/sequence ---------
 3625: #
 3626: #-------------------------------------------------------------------
 3627: 
 3628: #--------------------Scantron Grading-----------------------------------
 3629: #
 3630: #------ start of section for handling grading by page/sequence ---------
 3631: 
 3632: sub defaultFormData {
 3633:     my ($symb,$url)=@_;
 3634:     return '
 3635:       <input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
 3636:      '<input type="hidden" name="url"     value="'.$url.'" />'."\n".
 3637:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3638:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3639: }
 3640: 
 3641: sub getSequenceDropDown {
 3642:     my ($request,$symb)=@_;
 3643:     my $result='<select name="selectpage">'."\n";
 3644:     my ($titles,$symbx) = &getSymbMap($request);
 3645:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 3646:     my $ctr=0;
 3647:     foreach (@$titles) {
 3648: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 3649: 	$result.='<option value="'.$$symbx{$_}.'" '.
 3650: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="on"' : '').
 3651: 	    '>'.$showtitle.'</option>'."\n";
 3652: 	$ctr++;
 3653:     }
 3654:     $result.= '</select>';
 3655:     return $result;
 3656: }
 3657: 
 3658: sub scantron_filenames {
 3659:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3660:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3661:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 3662: 				    &Apache::loncommon::propath($cdom,$cname));
 3663:     my @possiblenames;
 3664:     foreach my $filename (sort(@files)) {
 3665: 	($filename)=split(/&/,$filename);
 3666: 	if ($filename!~/^scantron_orig_/) { next ; }
 3667: 	$filename=~s/^scantron_orig_//;
 3668: 	push(@possiblenames,$filename);
 3669:     }
 3670:     return @possiblenames;
 3671: }
 3672: 
 3673: sub scantron_uploads {
 3674:     my ($file2grade) = @_;
 3675:     my $result=	'<select name="scantron_selectfile">';
 3676:     $result.="<option></option>";
 3677:     foreach my $filename (sort(&scantron_filenames())) {
 3678: 	$result.="<option".($filename eq $file2grade ? ' selected="on"':'').">$filename</option>\n";
 3679:     }
 3680:     $result.="</select>";
 3681:     return $result;
 3682: }
 3683: 
 3684: sub scantron_scantab {
 3685:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 3686:     my $result='<select name="scantron_format">'."\n";
 3687:     $result.='<option></option>'."\n";
 3688:     foreach my $line (<$fh>) {
 3689: 	my ($name,$descrip)=split(/:/,$line);
 3690: 	if ($name =~ /^\#/) { next; }
 3691: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 3692:     }
 3693:     $result.='</select>'."\n";
 3694: 
 3695:     return $result;
 3696: }
 3697: 
 3698: sub scantron_CODElist {
 3699:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3700:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3701:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 3702:     my $namechoice='<option></option>';
 3703:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 3704: 	if ($name =~ /^error: 2 /) { next; }
 3705: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 3706:     }
 3707:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 3708:     return $namechoice;
 3709: }
 3710: 
 3711: sub scantron_CODEunique {
 3712:     my $result='<nobr>
 3713:                  <input type="radio" name="scantron_CODEunique"
 3714:                         value="Yes" checked="on" /> Yes
 3715:                 </nobr>
 3716:                 <nobr>
 3717:                  <input type="radio" name="scantron_CODEunique"
 3718:                         value="No" /> No
 3719:                 </nobr>';
 3720:     return $result;
 3721: }
 3722: 
 3723: sub scantron_selectphase {
 3724:     my ($r,$file2grade) = @_;
 3725:     my ($symb,$url)=&get_symb_and_url($r);
 3726:     if (!$symb) {return '';}
 3727:     my $sequence_selector=&getSequenceDropDown($r,$symb);
 3728:     my $default_form_data=&defaultFormData($symb,$url);
 3729:     my $grading_menu_button=&show_grading_menu_form($symb,$url);
 3730:     my $file_selector=&scantron_uploads($file2grade);
 3731:     my $format_selector=&scantron_scantab();
 3732:     my $CODE_selector=&scantron_CODElist();
 3733:     my $CODE_unique=&scantron_CODEunique();
 3734:     my $result;
 3735:     #FIXME allow instructor to be able to download the scantron file
 3736:     # and to upload it,
 3737:     $result.= <<SCANTRONFORM;
 3738:     <table width="100%" border="0">
 3739:     <tr>
 3740:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 3741:       <td bgcolor="#777777">
 3742:        <input type="hidden" name="command" value="scantron_warning" />
 3743:         $default_form_data
 3744:         <table width="100%" border="0">
 3745:           <tr bgcolor="#e6ffff">
 3746:             <td colspan="2">
 3747:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
 3748:             </td>
 3749:           </tr>
 3750:           <tr bgcolor="#ffffe6">
 3751:             <td> Sequence to grade: </td><td> $sequence_selector </td>
 3752:           </tr>
 3753:           <tr bgcolor="#ffffe6">
 3754:             <td> Filename of scoring office file: </td><td> $file_selector </td>
 3755:           </tr>
 3756:           <tr bgcolor="#ffffe6">
 3757:             <td> Format of data file: </td><td> $format_selector </td>
 3758:           </tr>
 3759:           <tr bgcolor="#ffffe6">
 3760:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
 3761:           </tr>
 3762:           <tr bgcolor="#ffffe6">
 3763:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
 3764:           </tr>
 3765:           <tr bgcolor="#ffffe6">
 3766: 	    <td> Options: </td>
 3767:             <td>
 3768:                 <input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records <br />
 3769:                 <input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all exisiting corrections
 3770: 	    </td>
 3771:           </tr>
 3772:           <tr bgcolor="#ffffe6">
 3773:             <td colspan="2">
 3774:               <input type="submit" value="Validate Scantron Records" />
 3775:             </td>
 3776:           </tr>
 3777:         </table>
 3778:        </td>
 3779:      </form>
 3780:     </tr>
 3781: SCANTRONFORM
 3782:    
 3783:     $r->print($result);
 3784: 
 3785:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 3786:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 3787: 
 3788:         $r->print(<<SCANTRONFORM);
 3789:     <tr>
 3790:       <td bgcolor="#777777">
 3791:         <table width="100%" border="0">
 3792:           <tr bgcolor="#e6ffff">
 3793:             <td>
 3794:               &nbsp;<b>Specify a Scantron data file to upload.</b>
 3795:             </td>
 3796:           </tr>
 3797:           <tr bgcolor="#ffffe6">
 3798:             <td>
 3799: SCANTRONFORM
 3800:     my $default_form_data=&defaultFormData(&get_symb_and_url($r,1));
 3801:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 3802:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 3803:     $r->print(<<UPLOAD);
 3804:               <script type="text/javascript" language="javascript">
 3805:     function checkUpload(formname) {
 3806: 	if (formname.upfile.value == "") {
 3807: 	    alert("Please use the browse button to select a file from your local directory.");
 3808: 	    return false;
 3809: 	}
 3810: 	formname.submit();
 3811:     }
 3812:               </script>
 3813: 
 3814:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
 3815:                 $default_form_data
 3816:                 <input name='courseid' type='hidden' value='$cnum' />
 3817:                 <input name='domainid' type='hidden' value='$cdom' />
 3818:                 <input name='command' value='scantronupload_save' type='hidden' />
 3819:                 File to upload:<input type="file" name="upfile" size="50" />
 3820:                 <br />
 3821:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
 3822:               </form>
 3823: UPLOAD
 3824: 
 3825:         $r->print(<<SCANTRONFORM);
 3826:             </td>
 3827:           </tr>
 3828:         </table>
 3829:       </td>
 3830:     </tr>
 3831: SCANTRONFORM
 3832:     }
 3833:     $r->print(<<SCANTRONFORM);
 3834:     <tr>
 3835:       <form action='/adm/grades' name='scantron_download'>
 3836:         <td bgcolor="#777777">
 3837:           <input type="hidden" name="command" value="scantron_download" />
 3838:           <table width="100%" border="0">
 3839:             <tr bgcolor="#e6ffff">
 3840:               <td colspan="2">
 3841:                 &nbsp;<b>Download a scoring office file</b>
 3842:               </td>
 3843:             </tr>
 3844:             <tr bgcolor="#ffffe6">
 3845:               <td> Filename of scoring office file: </td><td> $file_selector </td>
 3846:             </tr>
 3847:             <tr bgcolor="#ffffe6">
 3848:               <td colspan="2">
 3849:                 <input type="submit" value="Show List of Files" />
 3850:               </td>
 3851:             </tr>
 3852:           </table>
 3853:         </td>
 3854:       </form>
 3855:     </tr>
 3856: SCANTRONFORM
 3857: 
 3858:     $r->print(<<SCANTRONFORM);
 3859:   </table>
 3860: $grading_menu_button
 3861: SCANTRONFORM
 3862: 
 3863:     return
 3864: }
 3865: 
 3866: sub get_scantron_config {
 3867:     my ($which) = @_;
 3868:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 3869:     my %config;
 3870:     #FIXME probably should move to XML it has already gotten a bit much now
 3871:     foreach my $line (<$fh>) {
 3872: 	my ($name,$descrip)=split(/:/,$line);
 3873: 	if ($name ne $which ) { next; }
 3874: 	chomp($line);
 3875: 	my @config=split(/:/,$line);
 3876: 	$config{'name'}=$config[0];
 3877: 	$config{'description'}=$config[1];
 3878: 	$config{'CODElocation'}=$config[2];
 3879: 	$config{'CODEstart'}=$config[3];
 3880: 	$config{'CODElength'}=$config[4];
 3881: 	$config{'IDstart'}=$config[5];
 3882: 	$config{'IDlength'}=$config[6];
 3883: 	$config{'Qstart'}=$config[7];
 3884: 	$config{'Qlength'}=$config[8];
 3885: 	$config{'Qoff'}=$config[9];
 3886: 	$config{'Qon'}=$config[10];
 3887: 	$config{'PaperID'}=$config[11];
 3888: 	$config{'PaperIDlength'}=$config[12];
 3889: 	$config{'FirstName'}=$config[13];
 3890: 	$config{'FirstNamelength'}=$config[14];
 3891: 	$config{'LastName'}=$config[15];
 3892: 	$config{'LastNamelength'}=$config[16];
 3893: 	last;
 3894:     }
 3895:     return %config;
 3896: }
 3897: 
 3898: sub username_to_idmap {
 3899:     my ($classlist)= @_;
 3900:     my %idmap;
 3901:     foreach my $student (keys(%$classlist)) {
 3902: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 3903: 	    $student;
 3904:     }
 3905:     return %idmap;
 3906: }
 3907: 
 3908: sub scantron_fixup_scanline {
 3909:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 3910:     if ($field eq 'ID') {
 3911: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 3912: 	    return ($line,1,'New value too large');
 3913: 	}
 3914: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 3915: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 3916: 				     $args->{'newid'});
 3917: 	}
 3918: 	substr($line,$$scantron_config{'IDstart'}-1,
 3919: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 3920: 	if ($args->{'newid'}=~/^\s*$/) {
 3921: 	    &scan_data($scan_data,"$whichline.user",
 3922: 		       $args->{'username'}.':'.$args->{'domain'});
 3923: 	}
 3924:     } elsif ($field eq 'CODE') {
 3925: 	if ($args->{'CODE_ignore_dup'}) {
 3926: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 3927: 	}
 3928: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 3929: 	if ($args->{'CODE'} ne 'use_unfound') {
 3930: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 3931: 		return ($line,1,'New CODE value too large');
 3932: 	    }
 3933: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 3934: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 3935: 	    }
 3936: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 3937: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 3938: 	}
 3939:     } elsif ($field eq 'answer') {
 3940: 	my $length=$scantron_config->{'Qlength'};
 3941: 	my $off=$scantron_config->{'Qoff'};
 3942: 	my $on=$scantron_config->{'Qon'};
 3943: 	my $answer=${off}x$length;
 3944: 	if ($args->{'response'} eq 'none') {
 3945: 	    &scan_data($scan_data,
 3946: 		       "$whichline.no_bubble.".$args->{'question'},'1');
 3947: 	} else {
 3948: 	    substr($answer,$args->{'response'},1)=$on;
 3949: 	    &scan_data($scan_data,
 3950: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
 3951: 	}
 3952: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 3953: 	substr($line,$where-1,$length)=$answer;
 3954:     }
 3955:     return $line;
 3956: }
 3957: 
 3958: sub scan_data {
 3959:     my ($scan_data,$key,$value,$delete)=@_;
 3960:     my $filename=$env{'form.scantron_selectfile'};
 3961:     if (defined($value)) {
 3962: 	$scan_data->{$filename.'_'.$key} = $value;
 3963:     }
 3964:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 3965:     return $scan_data->{$filename.'_'.$key};
 3966: }
 3967: 
 3968: sub scantron_parse_scanline {
 3969:     my ($line,$whichline,$scantron_config,$scan_data,$justHeader)=@_;
 3970:     my %record;
 3971:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);
 3972:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);
 3973:     if ($$scantron_config{'CODElocation'} ne 0) {
 3974: 	if ($$scantron_config{'CODElocation'} < 0) {
 3975: 	    $record{'scantron.CODE'}=substr($data,
 3976: 					    $$scantron_config{'CODEstart'}-1,
 3977: 					    $$scantron_config{'CODElength'});
 3978: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 3979: 		$record{'scantron.useCODE'}=1;
 3980: 	    }
 3981: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 3982: 		$record{'scantron.CODE_ignore_dup'}=1;
 3983: 	    }
 3984: 	} else {
 3985: 	    #FIXME interpret first N questions
 3986: 	}
 3987:     }
 3988:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 3989: 				  $$scantron_config{'IDlength'});
 3990:     $record{'scantron.PaperID'}=
 3991: 	substr($data,$$scantron_config{'PaperID'}-1,
 3992: 	       $$scantron_config{'PaperIDlength'});
 3993:     $record{'scantron.FirstName'}=
 3994: 	substr($data,$$scantron_config{'FirstName'}-1,
 3995: 	       $$scantron_config{'FirstNamelength'});
 3996:     $record{'scantron.LastName'}=
 3997: 	substr($data,$$scantron_config{'LastName'}-1,
 3998: 	       $$scantron_config{'LastNamelength'});
 3999:     if ($justHeader) { return \%record; }
 4000: 
 4001:     my @alphabet=('A'..'Z');
 4002:     my $questnum=0;
 4003:     while ($questions) {
 4004: 	$questnum++;
 4005: 	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
 4006: 	substr($questions,0,$$scantron_config{'Qlength'})='';
 4007: 	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
 4008: 	if ($$scantron_config{'Qon'} eq 'letter') {
 4009: 	    if (!$currentquest || $currentquest eq $$scantron_config{'Qoff'} ||
 4010: 		$currentquest !~ /^[A-Z]$/) {
 4011: 		$record{"scantron.$questnum.answer"}='';
 4012: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
 4013: 		    push(@{$record{"scantron.missingerror"}},$questnum);
 4014: 		}
 4015: 	    } else {
 4016: 		$record{"scantron.$questnum.answer"}=$currentquest;
 4017: 	    }
 4018: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
 4019: 	    if (!$currentquest || $currentquest eq $$scantron_config{'Qoff'} ||
 4020: 		$currentquest !~ /^\d$/) {
 4021: 		$record{"scantron.$questnum.answer"}='';
 4022: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
 4023: 		    push(@{$record{"scantron.missingerror"}},$questnum);
 4024: 		}
 4025: 	    } else {
 4026: 		$record{"scantron.$questnum.answer"}=
 4027: 		    $alphabet[$currentquest-1];
 4028: 	    }
 4029: 	} else {
 4030: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
 4031: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}) {
 4032: 		$record{"scantron.$questnum.answer"}='';
 4033: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
 4034: 		    push(@{$record{"scantron.missingerror"}},$questnum);
 4035: 		}
 4036: 	    } else {
 4037: 		$record{"scantron.$questnum.answer"}=
 4038: 		    $alphabet[length($array[0])];
 4039: 	    }
 4040: 	    if (scalar(@array) gt 2) {
 4041: 		push(@{$record{'scantron.doubleerror'}},$questnum);
 4042: 		my @ans=@array;
 4043: 		my $i=length($ans[0]);shift(@ans);
 4044: 		while ($#ans) {
 4045: 		    $i+=length($ans[0])+1;
 4046: 		    $record{"scantron.$questnum.answer"}.=$alphabet[$i];
 4047: 		    shift(@ans);
 4048: 		}
 4049: 	    }
 4050: 	}
 4051:     }
 4052:     $record{'scantron.maxquest'}=$questnum;
 4053:     return \%record;
 4054: }
 4055: 
 4056: sub scantron_add_delay {
 4057:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 4058:     push(@$delayqueue,
 4059: 	 {'line' => $scanline, 'emsg' => $errormessage,
 4060: 	  'ecode' => $errorcode }
 4061: 	 );
 4062: }
 4063: 
 4064: sub scantron_find_student {
 4065:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 4066:     my $scanID=$$scantron_record{'scantron.ID'};
 4067:     if ($scanID =~ /^\s*$/) {
 4068:  	return &scan_data($scan_data,"$line.user");
 4069:     }
 4070:     foreach my $id (keys(%$idmap)) {
 4071:  	if (lc($id) eq lc($scanID)) {
 4072:  	    return $$idmap{$id};
 4073:  	}
 4074:     }
 4075:     return undef;
 4076: }
 4077: 
 4078: sub scantron_filter {
 4079:     my ($curres)=@_;
 4080:                         # randomout is dysfunctional at best for this purpose
 4081:     if (ref($curres) && $curres->is_problem()) { #&& !$curres->randomout) {
 4082: 	return 1;
 4083:     }
 4084:     return 0;
 4085: }
 4086: 
 4087: sub scantron_process_corrections {
 4088:     my ($r) = @_;
 4089:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 4090:     my ($scanlines,$scan_data)=&scantron_getfile();
 4091:     my $classlist=&Apache::loncoursedata::get_classlist();
 4092:     my $which=$env{'form.scantron_line'};
 4093:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 4094:     my ($skip,$err,$errmsg);
 4095:     if ($env{'form.scantron_skip_record'}) {
 4096: 	$skip=1;
 4097:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 4098: 	my $newstudent=$env{'form.scantron_username'}.':'.
 4099: 	    $env{'form.scantron_domain'};
 4100: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 4101: 	($line,$err,$errmsg)=
 4102: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 4103: 				     'ID',{'newid'=>$newid,
 4104: 				    'username'=>$env{'form.scantron_username'},
 4105: 				    'domain'=>$env{'form.scantron_domain'}});
 4106:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 4107: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 4108: 	my $newCODE;
 4109: 	my %args;
 4110: 	if      ($resolution eq 'use_unfound') {
 4111: 	    $newCODE='use_unfound';
 4112: 	} elsif ($resolution eq 'use_found') {
 4113: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 4114: 	} elsif ($resolution eq 'use_typed') {
 4115: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 4116: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 4117: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 4118: 	}
 4119: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 4120: 	    $args{'CODE_ignore_dup'}=1;
 4121: 	}
 4122: 	$args{'CODE'}=$newCODE;
 4123: 	($line,$err,$errmsg)=
 4124: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 4125: 				     'CODE',\%args);
 4126:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 4127: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 4128: 	    ($line,$err,$errmsg)=
 4129: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 4130: 					 $which,'answer',
 4131: 					 { 'question'=>$question,
 4132: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
 4133: 	    if ($err) { last; }
 4134: 	}
 4135:     }
 4136:     if ($err) {
 4137: 	$r->print("Unable to accept last correction, an error occurred :$errmsg:");
 4138:     } else {
 4139: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 4140: 	&scantron_putfile($scanlines,$scan_data);
 4141:     }
 4142: }
 4143: 
 4144: sub reset_skipping_status {
 4145:     my ($scanlines,$scan_data)=&scantron_getfile();
 4146:     &scan_data($scan_data,'remember_skipping',undef,1);
 4147:     &scantron_putfile(undef,$scan_data);
 4148: }
 4149: 
 4150: sub allow_skipping {
 4151:     my ($scan_data,$i)=@_;
 4152:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 4153:     delete($remembered{$i});
 4154:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 4155: }
 4156: 
 4157: sub should_be_skipped {
 4158:     my ($scan_data,$i)=@_;
 4159:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 4160: 	# not redoing old skips
 4161: 	return 0;
 4162:     }
 4163:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 4164:     if (exists($remembered{$i})) { return 0; }
 4165:     return 1;
 4166: }
 4167: 
 4168: sub remember_current_skipped {
 4169:     my ($scanlines,$scan_data)=&scantron_getfile();
 4170:     my %to_remember;
 4171:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 4172: 	if ($scanlines->{'skipped'}[$i]) {
 4173: 	    $to_remember{$i}=1;
 4174: 	}
 4175:     }
 4176:     &Apache::lonnet::logthis('remembering '.join(':',%to_remember));
 4177:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 4178:     &scantron_putfile(undef,$scan_data);
 4179: }
 4180: 
 4181: sub check_for_error {
 4182:     my ($r,$result)=@_;
 4183:     if ($result ne 'ok' && $result ne 'not_found' ) {
 4184: 	$r->print("An error occured ($result) when trying to Remove the existing corrections.");
 4185:     }
 4186: }
 4187: 
 4188: sub scantron_warning_screen {
 4189:     my ($button_text)=@_;
 4190:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 4191:     return (<<STUFF);
 4192: <p>
 4193: <font color="red">Please double check the information
 4194:                  below before clicking on '$button_text'</font>
 4195: </p>
 4196: <table>
 4197: <tr><td><b>Sequence To be Graded:</b></td><td>$title</td></tr>
 4198: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
 4199: </table>
 4200: </font>
 4201: <br />
 4202: <p> If this information is correct, please click on '$button_text'.</p>
 4203: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
 4204: 
 4205: <br />
 4206: STUFF
 4207: }
 4208: 
 4209: sub scantron_do_warning {
 4210:     my ($r)=@_;
 4211:     my ($symb,$url)=&get_symb_and_url($r);
 4212:     if (!$symb) {return '';}
 4213:     my $default_form_data=&defaultFormData($symb,$url);
 4214:     $r->print(&scantron_form_start().$default_form_data);
 4215:     if ( $env{'form.selectpage'} eq '' ||
 4216: 	 $env{'form.scantron_selectfile'} eq '' ||
 4217: 	 $env{'form.scantron_format'} eq '' ) {
 4218: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
 4219: 	if ( $env{'form.selectpage'} eq '') {
 4220: 	    $r->print('<p><font color="red">You have not selected a Sequence to grade</font></p>');
 4221: 	} 
 4222: 	if ( $env{'form.scantron_selectfile'} eq '') {
 4223: 	    $r->print('<p><font color="red">You have not selected a file that contains the student\'s response data.</font></p>');
 4224: 	} 
 4225: 	if ( $env{'form.scantron_format'} eq '') {
 4226: 	    $r->print('<p><font color="red">You have not selected a the format of the student\'s response data.</font></p>');
 4227: 	} 
 4228:     } else {
 4229: 	my $warning=&scantron_warning_screen('Validate Records');
 4230: 	$r->print(<<STUFF);
 4231: $warning
 4232: <input type="submit" name="submit" value="Validate Records" />
 4233: <input type="hidden" name="command" value="scantron_validate" />
 4234: STUFF
 4235:     }
 4236:     $r->print("</form><br />".&show_grading_menu_form($symb,$url)."</body></html>");
 4237:     return '';
 4238: }
 4239: 
 4240: sub scantron_form_start {
 4241:     my ($max_bubble)=@_;
 4242:     my $result= <<SCANTRONFORM;
 4243: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 4244:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 4245:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 4246:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 4247:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 4248:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 4249:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 4250:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 4251:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 4252: SCANTRONFORM
 4253:     return $result;
 4254: }
 4255: 
 4256: sub scantron_validate_file {
 4257:     my ($r) = @_;
 4258:     my ($symb,$url)=&get_symb_and_url($r);
 4259:     if (!$symb) {return '';}
 4260:     my $default_form_data=&defaultFormData($symb,$url);
 4261:     
 4262:     # do the detection of only doing skipped records first befroe we delete
 4263:     # them  when doing the corrections reset
 4264:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 4265: 	&reset_skipping_status();
 4266:     }
 4267:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 4268: 	&remember_current_skipped();
 4269: 	&scantron_remove_file('skipped');
 4270: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 4271:     }
 4272: 
 4273:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 4274: 	&check_for_error($r,&scantron_remove_file('corrected'));
 4275: 	&check_for_error($r,&scantron_remove_file('skipped'));
 4276: 	&check_for_error($r,&scantron_remove_scan_data());
 4277: 	$env{'form.scantron_options_ignore'}='done';
 4278:     }
 4279: 
 4280:     if ($env{'form.scantron_corrections'}) {
 4281: 	&scantron_process_corrections($r);
 4282:     }
 4283:     $r->print("<p>Gathering neccessary info.</p>");$r->rflush();
 4284:     #get the student pick code ready
 4285:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 4286:     my $max_bubble=&scantron_get_maxbubble($r);
 4287:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 4288:     $r->print($result);
 4289:     
 4290:     my @validate_phases=( 'ID',
 4291: 			  'CODE',
 4292: 			  'doublebubble',
 4293: 			  'missingbubbles');
 4294:     if (!$env{'form.validatepass'}) {
 4295: 	$env{'form.validatepass'} = 0;
 4296:     }
 4297:     my $currentphase=$env{'form.validatepass'};
 4298: 
 4299:     my $stop=0;
 4300:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 4301: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
 4302: 	$r->rflush();
 4303: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 4304: 	{
 4305: 	    no strict 'refs';
 4306: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 4307: 	}
 4308:     }
 4309:     if (!$stop) {
 4310: 	my $warning=&scantron_warning_screen('Start Grading');
 4311: 	$r->print(<<STUFF);
 4312: Validation process complete.<br />
 4313: $warning
 4314: <input type="submit" name="submit" value="Start Grading" />
 4315: <input type="hidden" name="command" value="scantron_process" />
 4316: STUFF
 4317: 
 4318:     } else {
 4319: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 4320: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 4321:     }
 4322:     if ($stop) {
 4323: 	$r->print('<input type="submit" name="submit" value="Continue ->" />');
 4324: 	$r->print(' using corrected info <br />');
 4325: 	$r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
 4326: 	$r->print(" this scanline saving it for later.");
 4327:     }
 4328:     $r->print(" </form><br />".&show_grading_menu_form($symb,$url).
 4329: 	      "</body></html>");
 4330:     return '';
 4331: }
 4332: 
 4333: sub scantron_remove_file {
 4334:     my ($which)=@_;
 4335:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4336:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4337:     my $file='scantron_';
 4338:     if ($which eq 'corrected' || $which eq 'skipped') {
 4339: 	$file.=$which.'_';
 4340:     } else {
 4341: 	return 'refused';
 4342:     }
 4343:     $file.=$env{'form.scantron_selectfile'};
 4344:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 4345: }
 4346: 
 4347: sub scantron_remove_scan_data {
 4348:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4349:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4350:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 4351:     my @todelete;
 4352:     my $filename=$env{'form.scantron_selectfile'};
 4353:     foreach my $key (@keys) {
 4354: 	if ($key=~/^\Q$filename\E_/) {
 4355: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 4356: 		$key=~/remember_skipping/) {
 4357: 		next;
 4358: 	    }
 4359: 	    push(@todelete,$key);
 4360: 	}
 4361:     }
 4362:     my $result;
 4363:     if (@todelete) {
 4364: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
 4365:     }
 4366:     return $result;
 4367: }
 4368: 
 4369: sub scantron_getfile {
 4370:     #FIXME really would prefer a scantron directory
 4371:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4372:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4373:     my $lines;
 4374:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 4375: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 4376:     my %scanlines;
 4377:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 4378:     my $temp=$scanlines{'orig'};
 4379:     $scanlines{'count'}=$#$temp;
 4380: 
 4381:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 4382: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 4383:     if ($lines eq '-1') {
 4384: 	$scanlines{'corrected'}=[];
 4385:     } else {
 4386: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 4387:     }
 4388:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 4389: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 4390:     if ($lines eq '-1') {
 4391: 	$scanlines{'skipped'}=[];
 4392:     } else {
 4393: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 4394:     }
 4395:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 4396:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 4397:     my %scan_data = @tmp;
 4398:     return (\%scanlines,\%scan_data);
 4399: }
 4400: 
 4401: sub lonnet_putfile {
 4402:     my ($contents,$filename)=@_;
 4403:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4404:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4405:     my $docuhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4406:     $env{'form.sillywaytopassafilearound'}=$contents;
 4407:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,$docuhome,'sillywaytopassafilearound',$filename);
 4408: 
 4409: }
 4410: 
 4411: sub scantron_putfile {
 4412:     my ($scanlines,$scan_data) = @_;
 4413:     #FIXME really would prefer a scantron directory
 4414:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4415:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4416:     if ($scanlines) {
 4417: 	my $prefix='scantron_';
 4418: # no need to update orig, shouldn't change
 4419: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 4420: #		    $env{'form.scantron_selectfile'});
 4421: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 4422: 			$prefix.'corrected_'.
 4423: 			$env{'form.scantron_selectfile'});
 4424: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 4425: 			$prefix.'skipped_'.
 4426: 			$env{'form.scantron_selectfile'});
 4427:     }
 4428:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 4429: }
 4430: 
 4431: sub scantron_get_line {
 4432:     my ($scanlines,$scan_data,$i)=@_;
 4433:     if (&should_be_skipped($scan_data,$i)) { return undef; }
 4434:     if ($scanlines->{'skipped'}[$i]) { return undef; }
 4435:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 4436:     return $scanlines->{'orig'}[$i]; 
 4437: }
 4438: 
 4439: sub get_todo_count {
 4440:     my ($scanlines,$scan_data)=@_;
 4441:     my $count=0;
 4442:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 4443: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 4444: 	if ($line=~/^[\s\cz]*$/) { next; }
 4445: 	$count++;
 4446:     }
 4447:     return $count;
 4448: }
 4449: 
 4450: sub scantron_put_line {
 4451:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 4452:     if ($skip) {
 4453: 	$scanlines->{'skipped'}[$i]=$newline;
 4454: 	&allow_skipping($scan_data,$i);
 4455: 	return;
 4456:     }
 4457:     $scanlines->{'corrected'}[$i]=$newline;
 4458: }
 4459: 
 4460: sub scantron_validate_ID {
 4461:     my ($r,$currentphase) = @_;
 4462:     
 4463:     #get student info
 4464:     my $classlist=&Apache::loncoursedata::get_classlist();
 4465:     my %idmap=&username_to_idmap($classlist);
 4466: 
 4467:     #get scantron line setup
 4468:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 4469:     my ($scanlines,$scan_data)=&scantron_getfile();
 4470: 
 4471:     my %found=('ids'=>{},'usernames'=>{});
 4472:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 4473: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 4474: 	if ($line=~/^[\s\cz]*$/) { next; }
 4475: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 4476: 						 $scan_data);
 4477: 	my $id=$$scan_record{'scantron.ID'};
 4478: 	my $found;
 4479: 	foreach my $checkid (keys(%idmap)) {
 4480: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 4481: 	}
 4482: 	if ($found) {
 4483: 	    my $username=$idmap{$found};
 4484: 	    if ($found{'ids'}{$found}) {
 4485: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 4486: 					 $line,'duplicateID',$found);
 4487: 		return(1,$currentphase);
 4488: 	    } elsif ($found{'usernames'}{$username}) {
 4489: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 4490: 					 $line,'duplicateID',$username);
 4491: 		return(1,$currentphase);
 4492: 	    }
 4493: 	    #FIXME store away line we previously saw the ID on to use above
 4494: 	    $found{'ids'}{$found}++;
 4495: 	    $found{'usernames'}{$username}++;
 4496: 	} else {
 4497: 	    if ($id =~ /^\s*$/) {
 4498: 		my $username=&scan_data($scan_data,"$i.user");
 4499: 		if (defined($username) && $found{'usernames'}{$username}) {
 4500: 		    &scantron_get_correction($r,$i,$scan_record,
 4501: 					     \%scantron_config,
 4502: 					     $line,'duplicateID',$username);
 4503: 		    return(1,$currentphase);
 4504: 		} elsif (!defined($username)) {
 4505: 		    &scantron_get_correction($r,$i,$scan_record,
 4506: 					     \%scantron_config,
 4507: 					     $line,'incorrectID');
 4508: 		    return(1,$currentphase);
 4509: 		}
 4510: 		$found{'usernames'}{$username}++;
 4511: 	    } else {
 4512: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 4513: 					 $line,'incorrectID');
 4514: 		return(1,$currentphase);
 4515: 	    }
 4516: 	}
 4517:     }
 4518: 
 4519:     return (0,$currentphase+1);
 4520: }
 4521: 
 4522: sub scantron_get_correction {
 4523:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 4524: 
 4525: #FIXME in the case of a duplicated ID the previous line, probaly need
 4526: #to show both the current line and the previous one and allow skipping
 4527: #the previous one or the current one
 4528: 
 4529:     $r->print("<p><b>An error was detected ($error)</b>");
 4530:     if ( defined($$scan_record{'scantron.PaperID'}) ) {
 4531: 	$r->print(" for PaperID <tt>".
 4532: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
 4533:     } else {
 4534: 	$r->print(" in scanline $i <pre>".
 4535: 		  $line."</pre> \n");
 4536:     }
 4537:     my $message="<p>The ID on the form is  <tt>".
 4538: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
 4539: 	"The name on the paper is ".
 4540: 	$$scan_record{'scantron.LastName'}.",".
 4541: 	$$scan_record{'scantron.FirstName'}."</p>";
 4542: 
 4543:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 4544:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 4545:     if ($error =~ /ID$/) {
 4546: 	if ($error eq 'incorrectID') {
 4547: 	    $r->print("The encoded ID is not in the classlist</p>\n");
 4548: 	} elsif ($error eq 'duplicateID') {
 4549: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
 4550: 	}
 4551: 	$r->print($message);
 4552: 	$r->print("<p>How should I handle this? <br /> \n");
 4553: 	$r->print("\n<ul><li> ");
 4554: 	#FIXME it would be nice if this sent back the user ID and
 4555: 	#could do partial userID matches
 4556: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 4557: 				       'scantron_username','scantron_domain'));
 4558: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 4559: 	$r->print("\n@".
 4560: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 4561: 
 4562: 	$r->print('</li>');
 4563:     } elsif ($error =~ /CODE$/) {
 4564: 	if ($error eq 'incorrectCODE') {
 4565: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
 4566: 	} elsif ($error eq 'duplicateCODE') {
 4567: 	    $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");
 4568: 	}
 4569: 	$r->print("<p>The CODE on the form is  <tt>'".
 4570: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
 4571: 	$r->print($message);
 4572: 	$r->print("<p>How should I handle this? <br /> \n");
 4573: 	$r->print("\n<br /> ");
 4574: 	my $i=0;
 4575: 	if ($error eq 'incorrectCODE') {
 4576: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 4577: 	    foreach my $testcode (@{$closest}) {
 4578: 		my $checked='';
 4579: 		if (!$i) { $checked=' checked="on" '; }
 4580: 		$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' />");
 4581: 		$r->print("\n<br />");
 4582: 		$i++;
 4583: 	    }
 4584: 	}
 4585: 	my $checked; if (!$i) { $checked=' checked="on" '; }
 4586: 	$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.");
 4587: 	$r->print("\n<br />");
 4588: 
 4589: 	$r->print(<<ENDSCRIPT);
 4590: <script type="text/javascript">
 4591: function change_radio(field) {
 4592:     var slct=document.scantronupload.scantron_CODE_resolution;
 4593:     var i;
 4594:     for (i=0;i<slct.length;i++) {
 4595:         if (slct[i].value==field) { slct[i].checked=true; }
 4596:     }
 4597: }
 4598: </script>
 4599: ENDSCRIPT
 4600: 	my $href="/adm/pickcode?".
 4601: 	   "form=".&Apache::lonnet::escape("scantronupload").
 4602: 	   "&scantron_format=".&Apache::lonnet::escape($env{'form.scantron_format'}).
 4603: 	   "&scantron_CODElist=".&Apache::lonnet::escape($env{'form.scantron_CODElist'}).
 4604: 	   "&curCODE=".&Apache::lonnet::escape($$scan_record{'scantron.CODE'}).
 4605: 	   "&scantron_selectfile=".&Apache::lonnet::escape($env{'form.scantron_selectfile'});
 4606: 	$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')\" />");
 4607: 	$r->print("\n<br />");
 4608: 	$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.");
 4609: 	$r->print("\n<br /><br />");
 4610:     } elsif ($error eq 'doublebubble') {
 4611: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
 4612: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 4613: 		  join(',',@{$arg}).'" />');
 4614: 	$r->print($message);
 4615: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
 4616: 	foreach my $question (@{$arg}) {
 4617: 	    my $selected=$$scan_record{"scantron.$question.answer"};
 4618: 	    &scantron_bubble_selector($r,$scan_config,$question,split('',$selected));
 4619: 	}
 4620:     } elsif ($error eq 'missingbubble') {
 4621: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
 4622: 	$r->print($message);
 4623: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
 4624: 	$r->print("Some questions have no scanned bubbles\n");
 4625: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 4626: 		  join(',',@{$arg}).'" />');
 4627: 	foreach my $question (@{$arg}) {
 4628: 	    my $selected=$$scan_record{"scantron.$question.answer"};
 4629: 	    &scantron_bubble_selector($r,$scan_config,$question);
 4630: 	}
 4631:     } else {
 4632: 	$r->print("\n<ul>");
 4633:     }
 4634:     $r->print("\n</li></ul>");
 4635: 
 4636: }
 4637: 
 4638: sub scantron_bubble_selector {
 4639:     my ($r,$scan_config,$quest,@selected)=@_;
 4640:     my $max=$$scan_config{'Qlength'};
 4641:     my @alphabet=('A'..'Z');
 4642:     $r->print("<table border='1'><tr><td rowspan='2'>$quest</td>");
 4643:     for (my $i=0;$i<$max+1;$i++) {
 4644: 	$r->print('<td align="center">');
 4645: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
 4646: 	else { $r->print('&nbsp;'); }
 4647: 	$r->print('</td>');
 4648:     }
 4649:     $r->print('<td></td></tr><tr>');
 4650:     for (my $i=0;$i<$max;$i++) {
 4651: 	$r->print('<td><input type="radio" name="scantron_correct_Q_'.$quest.
 4652: 		  '" value="'.$i.'" />'.$alphabet[$i]."</td>");
 4653:     }
 4654:     $r->print('<td><input type="radio" name="scantron_correct_Q_'.$quest.
 4655: 	      '" value="none" /> No bubble </td>');
 4656:     $r->print('</tr></table>');
 4657: }
 4658: 
 4659: sub num_matches {
 4660:     my ($orig,$code) = @_;
 4661:     my @code=split(//,$code);
 4662:     my @orig=split(//,$orig);
 4663:     my $same=0;
 4664:     for (my $i=0;$i<scalar(@code);$i++) {
 4665: 	if ($code[$i] eq $orig[$i]) { $same++; }
 4666:     }
 4667:     return $same;
 4668: }
 4669: 
 4670: sub scantron_get_closely_matching_CODEs {
 4671:     my ($allcodes,$CODE)=@_;
 4672:     my @CODEs;
 4673:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 4674: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 4675:     }
 4676: 
 4677:     return ($#CODEs,$CODEs[-1]);
 4678: }
 4679: 
 4680: sub get_codes {
 4681:     my $old_name=$env{'form.scantron_CODElist'};
 4682:     my $cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 4683:     my $cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 4684:     my %result=&Apache::lonnet::get('CODEs',[$old_name],$cdom,$cnum);
 4685:     my %allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 4686:     return %allcodes;
 4687: }
 4688: 
 4689: sub scantron_validate_CODE {
 4690:     my ($r,$currentphase) = @_;
 4691:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 4692:     if ($scantron_config{'CODElocation'} &&
 4693: 	$scantron_config{'CODEstart'} &&
 4694: 	$scantron_config{'CODElength'}) {
 4695: 	if (!defined($env{'form.scantron_CODElist'})) {
 4696: 	    &FIXME_blow_up()
 4697: 	}
 4698:     } else {
 4699: 	return (0,$currentphase+1);
 4700:     }
 4701:     
 4702:     my %usedCODEs;
 4703: 
 4704:     my %allcodes=&get_codes();
 4705: 
 4706:     my ($scanlines,$scan_data)=&scantron_getfile();
 4707:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 4708: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 4709: 	if ($line=~/^[\s\cz]*$/) { next; }
 4710: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 4711: 						 $scan_data);
 4712: 	my $CODE=$$scan_record{'scantron.CODE'};
 4713: 	my $error=0;
 4714: 	if (!&Apache::lonnet::validCODE($CODE)) {
 4715: 	    &scantron_get_correction($r,$i,$scan_record,
 4716: 				     \%scantron_config,
 4717: 				     $line,'incorrectCODE',\%allcodes);
 4718: 	    return(1,$currentphase);
 4719: 	}
 4720: 	if (%allcodes && !exists($allcodes{$CODE}) 
 4721: 	    && !$$scan_record{'scantron.useCODE'}) {
 4722: 	    &scantron_get_correction($r,$i,$scan_record,
 4723: 				     \%scantron_config,
 4724: 				     $line,'incorrectCODE',\%allcodes);
 4725: 	    return(1,$currentphase);
 4726: 	}
 4727: 	if (exists($usedCODEs{$CODE}) 
 4728: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 4729: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 4730: 	    &scantron_get_correction($r,$i,$scan_record,
 4731: 				     \%scantron_config,
 4732: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 4733: 	    return(1,$currentphase);
 4734: 	}
 4735: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 4736:     }
 4737:     return (0,$currentphase+1);
 4738: }
 4739: 
 4740: sub scantron_validate_doublebubble {
 4741:     my ($r,$currentphase) = @_;
 4742:     #get student info
 4743:     my $classlist=&Apache::loncoursedata::get_classlist();
 4744:     my %idmap=&username_to_idmap($classlist);
 4745: 
 4746:     #get scantron line setup
 4747:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 4748:     my ($scanlines,$scan_data)=&scantron_getfile();
 4749:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 4750: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 4751: 	if ($line=~/^[\s\cz]*$/) { next; }
 4752: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 4753: 						 $scan_data);
 4754: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 4755: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 4756: 				 'doublebubble',
 4757: 				 $$scan_record{'scantron.doubleerror'});
 4758:     	return (1,$currentphase);
 4759:     }
 4760:     return (0,$currentphase+1);
 4761: }
 4762: 
 4763: sub scantron_get_maxbubble {
 4764:     my ($r)=@_;
 4765:     if (defined($env{'form.scantron_maxbubble'}) &&
 4766: 	$env{'form.scantron_maxbubble'}) {
 4767: 	return $env{'form.scantron_maxbubble'};
 4768:     }
 4769:     my $navmap=Apache::lonnavmaps::navmap->new();
 4770:     my (undef,undef,$sequence)=
 4771: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 4772:     my $map=$navmap->getResourceByUrl($sequence);
 4773:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 4774:     &Apache::lonnet::delenv('form.counter');
 4775:     foreach my $resource (@resources) {
 4776: 	my $result=&Apache::lonnet::ssi($resource->src().'?symb='.&Apache::lonnet::escape($resource->symb()));
 4777:     }
 4778:     &Apache::lonnet::delenv('scantron\.');
 4779:     my $envfile=$env{'user.environment'};
 4780:     $envfile=~/\/([^\/]+)\.id$/;
 4781:     $envfile=$1;
 4782:     &Apache::lonnet::transfer_profile_to_env($r->dir_config('lonIDsDir'),
 4783: 					     $envfile);
 4784:     $env{'form.scantron_maxbubble'}=$env{'form.counter'}-1;
 4785:     return $env{'form.scantron_maxbubble'};
 4786: }
 4787: 
 4788: sub scantron_validate_missingbubbles {
 4789:     my ($r,$currentphase) = @_;
 4790:     #get student info
 4791:     my $classlist=&Apache::loncoursedata::get_classlist();
 4792:     my %idmap=&username_to_idmap($classlist);
 4793: 
 4794:     #get scantron line setup
 4795:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 4796:     my ($scanlines,$scan_data)=&scantron_getfile();
 4797:     my $max_bubble=&scantron_get_maxbubble();
 4798:     if (!$max_bubble) { $max_bubble=2**31; }
 4799:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 4800: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 4801: 	if ($line=~/^[\s\cz]*$/) { next; }
 4802: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 4803: 						 $scan_data);
 4804: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 4805: 	my @to_correct;
 4806: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 4807: 	    if ($missing > $max_bubble) { next; }
 4808: 	    push(@to_correct,$missing);
 4809: 	}
 4810: 	if (@to_correct) {
 4811: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 4812: 				     $line,'missingbubble',\@to_correct);
 4813: 	    return (1,$currentphase);
 4814: 	}
 4815: 
 4816:     }
 4817:     return (0,$currentphase+1);
 4818: }
 4819: 
 4820: sub scantron_process_students {
 4821:     my ($r) = @_;
 4822:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 4823:     my ($symb,$url)=&get_symb_and_url($r);
 4824:     if (!$symb) {return '';}
 4825:     my $default_form_data=&defaultFormData($symb,$url);
 4826: 
 4827:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 4828:     my ($scanlines,$scan_data)=&scantron_getfile();
 4829:     my $classlist=&Apache::loncoursedata::get_classlist();
 4830:     my %idmap=&username_to_idmap($classlist);
 4831:     my $navmap=Apache::lonnavmaps::navmap->new();
 4832:     my $map=$navmap->getResourceByUrl($sequence);
 4833:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 4834: #    $r->print("geto ".scalar(@resources)."<br />");
 4835:     my $result= <<SCANTRONFORM;
 4836: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 4837:   <input type="hidden" name="command" value="scantron_configphase" />
 4838:   $default_form_data
 4839: SCANTRONFORM
 4840:     $r->print($result);
 4841: 
 4842:     my @delayqueue;
 4843:     my %completedstudents;
 4844:     
 4845:     my $count=&get_todo_count($scanlines,$scan_data);
 4846:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 4847:  				    'Scantron Progress',$count,
 4848: 				    'inline',undef,'scantronupload');
 4849:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 4850: 					  'Processing first student');
 4851:     my $start=&Time::HiRes::time();
 4852:     my $i=-1;
 4853:     my ($uname,$udom,$started);
 4854:     while ($i<$scanlines->{'count'}) {
 4855:  	($uname,$udom)=('','');
 4856:  	$i++;
 4857:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 4858:  	if ($line=~/^[\s\cz]*$/) { next; }
 4859: 	if ($started) {
 4860: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 4861: 						     'last student');
 4862: 	}
 4863: 	$started=1;
 4864:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 4865:  						 $scan_data);
 4866:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 4867:  					      \%idmap,$i)) {
 4868:   	    &scantron_add_delay(\@delayqueue,$line,
 4869:  				'Unable to find a student that matches',1);
 4870:  	    next;
 4871:   	}
 4872:  	if (exists $completedstudents{$uname}) {
 4873:  	    &scantron_add_delay(\@delayqueue,$line,
 4874:  				'Student '.$uname.' has multiple sheets',2);
 4875:  	    next;
 4876:  	}
 4877:   	($uname,$udom)=split(/:/,$uname);
 4878:   	&Apache::lonnet::delenv('form.counter');
 4879:   	&Apache::lonnet::appenv(%$scan_record);
 4880: 	
 4881: 	my $i=0;
 4882: 	foreach my $resource (@resources) {
 4883: 	    $i++;
 4884: 	    my %form=('submitted'     =>'scantron',
 4885: 		      'grade_target'  =>'grade',
 4886: 		      'grade_username'=>$uname,
 4887: 		      'grade_domain'  =>$udom,
 4888: 		      'grade_courseid'=>$env{'request.course.id'},
 4889: 		      'grade_symb'    =>$resource->symb());
 4890: 	    if (exists($scan_record->{'scantron.CODE'}) &&
 4891: 		$scan_record->{'scantron.CODE'}) {
 4892: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
 4893: 	    } else {
 4894: 		$form{'CODE'}='';
 4895: 	    }
 4896: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
 4897: 	    if ($result ne '') {
 4898: 		&Apache::lonnet::logthis("scantron grading error -> $result");
 4899: 		&Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
 4900: 	    }
 4901: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
 4902: 	}
 4903: 	$completedstudents{$uname}={'line'=>$line};
 4904: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
 4905:     } continue {
 4906: 	&Apache::lonnet::delenv('form.counter');
 4907: 	&Apache::lonnet::delenv('scantron\.');
 4908:     }
 4909:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 4910: #    my $lasttime = &Time::HiRes::time()-$start;
 4911: #    $r->print("<p>took $lasttime</p>");
 4912: 
 4913:     $r->print("</form>");
 4914:     $r->print(&show_grading_menu_form($symb,$url));
 4915:     return '';
 4916: }
 4917: 
 4918: sub scantron_upload_scantron_data {
 4919:     my ($r)=@_;
 4920:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 4921:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 4922: 							  'domainid',
 4923: 							  'coursename');
 4924:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 4925: 						   'domainid');
 4926:     my $default_form_data=&defaultFormData(&get_symb_and_url($r,1));
 4927:     $r->print(<<UPLOAD);
 4928: <script type="text/javascript" language="javascript">
 4929:     function checkUpload(formname) {
 4930: 	if (formname.upfile.value == "") {
 4931: 	    alert("Please use the browse button to select a file from your local directory.");
 4932: 	    return false;
 4933: 	}
 4934: 	formname.submit();
 4935:     }
 4936: </script>
 4937: 
 4938: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
 4939: $default_form_data
 4940: <table>
 4941: <tr><td>$select_link </td></tr>
 4942: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
 4943: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
 4944: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
 4945: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
 4946: </table>
 4947: <input name='command' value='scantronupload_save' type='hidden' />
 4948: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
 4949: </form>
 4950: UPLOAD
 4951:     return '';
 4952: }
 4953: 
 4954: sub scantron_upload_scantron_data_save {
 4955:     my($r)=@_;
 4956:     my ($symb,$url)=&get_symb_and_url($r,1);
 4957:     my $doanotherupload=
 4958: 	'<br /><form action="/adm/grades" method="post">'."\n".
 4959: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 4960: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
 4961: 	'</form>'."\n";
 4962:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 4963: 	!&Apache::lonnet::allowed('usc',
 4964: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 4965: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
 4966: 	if ($symb) {
 4967: 	    $r->print(&show_grading_menu_form($symb,$url));
 4968: 	} else {
 4969: 	    $r->print($doanotherupload);
 4970: 	}
 4971: 	return '';
 4972:     }
 4973:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 4974:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
 4975:     my $home=&Apache::lonnet::homeserver($env{'form.courseid'},
 4976: 					 $env{'form.domainid'});
 4977:     my $fname=$env{'form.upfile.filename'};
 4978:     #FIXME
 4979:     #copied from lonnet::userfileupload()
 4980:     #make that function able to target a specified course
 4981:     # Replace Windows backslashes by forward slashes
 4982:     $fname=~s/\\/\//g;
 4983:     # Get rid of everything but the actual filename
 4984:     $fname=~s/^.*\/([^\/]+)$/$1/;
 4985:     # Replace spaces by underscores
 4986:     $fname=~s/\s+/\_/g;
 4987:     # Replace all other weird characters by nothing
 4988:     $fname=~s/[^\w\.\-]//g;
 4989:     # See if there is anything left
 4990:     unless ($fname) { return 'error: no uploaded file'; }
 4991:     my $uploadedfile=$fname;
 4992:     $fname='scantron_orig_'.$fname;
 4993:     if (length($env{'form.upfile'}) < 2) {
 4994: 	$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.");
 4995:     } else {
 4996: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},$home,'upfile',$fname);
 4997: 	if ($result =~ m|^/uploaded/|) {
 4998: 	    $r->print("<font color='green'>Success:</font> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
 4999: 	} else {
 5000: 	    $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>");
 5001: 	}
 5002:     }
 5003:     if ($symb) {
 5004: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 5005:     } else {
 5006: 	$r->print($doanotherupload);
 5007:     }
 5008:     return '';
 5009: }
 5010: 
 5011: sub valid_file {
 5012:     my ($requested_file)=@_;
 5013:     foreach my $filename (sort(&scantron_filenames())) {
 5014: 	&Apache::lonnet::logthis("$requested_file  $filename");
 5015: 	if ($requested_file eq $filename) { return 1; }
 5016:     }
 5017:     return 0;
 5018: }
 5019: 
 5020: sub scantron_download_scantron_data {
 5021:     my ($r)=@_;
 5022:     my $default_form_data=&defaultFormData(&get_symb_and_url($r,1));
 5023:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5024:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5025:     my $file=$env{'form.scantron_selectfile'};
 5026:     if (! &valid_file($file)) {
 5027: 	$r->print(<<ERROR);
 5028: 	<p>
 5029: 	    The requested file name was invalid.
 5030:         </p>
 5031: ERROR
 5032: 	$r->print(&show_grading_menu_form(&get_symb_and_url($r,1)));
 5033: 	return;
 5034:     }
 5035:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 5036:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 5037:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 5038:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 5039:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 5040:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 5041:     $r->print(<<DOWNLOAD);
 5042:     <p>
 5043: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
 5044:     </p>
 5045:     <p>
 5046: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
 5047:     </p>
 5048:     <p>
 5049: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
 5050:     </p>
 5051: DOWNLOAD
 5052:     $r->print(&show_grading_menu_form(&get_symb_and_url($r,1)));
 5053:     return '';
 5054: }
 5055: 
 5056: #-------- end of section for handling grading scantron forms -------
 5057: #
 5058: #-------------------------------------------------------------------
 5059: 
 5060: #-------------------------- Menu interface -------------------------
 5061: #
 5062: #--- Show a Grading Menu button - Calls the next routine ---
 5063: sub show_grading_menu_form {
 5064:     my ($symb,$url)=@_;
 5065:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 5066: 	'<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
 5067: 	'<input type="hidden" name="url" value="'.$url.'" />'."\n".
 5068: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 5069: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 5070: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
 5071: 	'</form>'."\n";
 5072:     return $result;
 5073: }
 5074: 
 5075: # -- Retrieve choices for grading form
 5076: sub savedState {
 5077:     my %savedState = ();
 5078:     if ($env{'form.saveState'}) {
 5079: 	foreach (split(/:/,$env{'form.saveState'})) {
 5080: 	    my ($key,$value) = split(/=/,$_,2);
 5081: 	    $savedState{$key} = $value;
 5082: 	}
 5083:     }
 5084:     return \%savedState;
 5085: }
 5086: 
 5087: #--- Displays the main menu page -------
 5088: sub gradingmenu {
 5089:     my ($request) = @_;
 5090:     my ($symb,$url)=&get_symb_and_url($request);
 5091:     if (!$symb) {return '';}
 5092:     my $probTitle = &Apache::lonnet::gettitle($symb);
 5093: 
 5094:     $request->print(<<GRADINGMENUJS);
 5095: <script type="text/javascript" language="javascript">
 5096:     function checkChoice(formname,val,cmdx) {
 5097: 	if (val <= 2) {
 5098: 	    var cmd = radioSelection(formname.radioChoice);
 5099: 	    var cmdsave = cmd;
 5100: 	} else {
 5101: 	    cmd = cmdx;
 5102: 	    cmdsave = 'submission';
 5103: 	}
 5104: 	formname.command.value = cmd;
 5105: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 5106: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 5107: 	if (val < 5) formname.submit();
 5108: 	if (val == 5) {
 5109: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 5110: 	    formname.submit();
 5111: 	}
 5112: 	if (val < 7) formname.submit();
 5113:     }
 5114: 
 5115:     function checkReceiptNo(formname,nospace) {
 5116: 	var receiptNo = formname.receipt.value;
 5117: 	var checkOpt = false;
 5118: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 5119: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 5120: 	if (checkOpt) {
 5121: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 5122: 	    formname.receipt.value = "";
 5123: 	    formname.receipt.focus();
 5124: 	    return false;
 5125: 	}
 5126: 	return true;
 5127:     }
 5128: </script>
 5129: GRADINGMENUJS
 5130:     &commonJSfunctions($request);
 5131:     my $result='<h3>&nbsp;<font color="#339933">Manual Grading/View Submission</font></h3>';
 5132:     my ($table,undef,$hdgrade) = &showResourceInfo($url,$probTitle);
 5133:     $result.=$table;
 5134:     my (undef,$sections) = &getclasslist('all','0');
 5135:     my $savedState = &savedState();
 5136:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 5137:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 5138:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 5139:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 5140: 
 5141:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 5142: 	'<input type="hidden" name="symb"        value="'.$symb.'" />'."\n".
 5143: 	'<input type="hidden" name="url"         value="'.$url.'" />'."\n".
 5144: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 5145: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 5146: 	'<input type="hidden" name="command"     value="" />'."\n".
 5147: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 5148: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 5149: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 5150: 
 5151:     $result.='<table width="100%" border=0><tr><td bgcolor=#777777>'."\n".
 5152: 	'<table width=100% border=0><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
 5153: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
 5154: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
 5155: 
 5156:     $result.='<table width="100%" border=0>';
 5157:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
 5158: 	'&nbsp;'.&mt('Select Section').': <select name="section">'."\n";
 5159:     if (ref($sections)) {
 5160: 	foreach (sort (@$sections)) {
 5161: 	    $result.='<option value="'.$_.'" '.
 5162: 		($saveSec eq $_ ? 'selected="on"':'').'>'.$_.'</option>'."\n";
 5163: 	}
 5164:     }
 5165:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="on"' : ''). '>all</option></select> &nbsp; ';
 5166: 
 5167:     $result.=&mt('Student Status').':</b>'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
 5168: 
 5169:     $result.='</td></tr>';
 5170: 
 5171:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
 5172: 	'<input type="radio" name="radioChoice" value="submission" '.
 5173: 	($saveCmd eq 'submission' ? 'checked' : '').'> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
 5174: 	' <select name="submitonly">'.
 5175: 	'<option value="yes" '.
 5176: 	($saveSub eq 'yes' ? 'selected="on"' : '').'>with submissions</option>'.
 5177: 	'<option value="graded" '.
 5178: 	($saveSub eq 'graded' ? 'selected="on"' : '').'>with ungraded submissions</option>'.
 5179: 	'<option value="incorrect" '.
 5180: 	($saveSub eq 'incorrect' ? 'selected="on"' : '').'>with incorrect submissions</option>'.
 5181: 	'<option value="all" '.
 5182: 	($saveSub eq 'all' ? 'selected="on"' : '').'>with any status</option></select></td></tr>'."\n";
 5183: 
 5184:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
 5185: 	'<input type="radio" name="radioChoice" value="viewgrades" '.
 5186: 	($saveCmd eq 'viewgrades' ? 'checked' : '').'> '.
 5187: 	'<b>Current Resource:</b> For all students in selected section or course</td></tr>'."\n";
 5188: 
 5189:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
 5190: 	'<input type="radio" name="radioChoice" value="pickStudentPage" '.
 5191: 	($saveCmd eq 'pickStudentPage' ? 'checked' : '').'> '.
 5192: 	'The <b>complete</b> set/page/sequence: For one student</td></tr>'."\n";
 5193: 
 5194:     $result.='<tr bgcolor="#ffffe6"><td><br />'.
 5195: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
 5196: 	'</td></tr></table>'."\n";
 5197: 
 5198:     $result.='</td><td valign="top">';
 5199: 
 5200:     $result.='<table width="100%" border=0>';
 5201:     $result.='<tr bgcolor="#ffffe6"><td>'.
 5202: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
 5203: 	' '.&mt('scores from file').' </td></tr>'."\n";
 5204: 
 5205:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 5206: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
 5207: 	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
 5208: 
 5209:     if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
 5210: 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
 5211: 	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
 5212: 	    ' '.&mt('receipt').': '.
 5213: 	    &Apache::lonnet::recprefix($env{'request.course.id'}).
 5214: 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')">'.
 5215: 	    '</td></tr>'."\n";
 5216:     } 
 5217:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 5218: 	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
 5219: 	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
 5220: 
 5221:     $result.='</form></td></tr></table>'."\n".
 5222: 	'</td></tr></table>'."\n".
 5223: 	'</td></tr></table>'."\n";
 5224:     return $result;
 5225: }
 5226: 
 5227: sub handler {
 5228:     my $request=$_[0];
 5229: 
 5230:     undef(%perm);
 5231:     if ($env{'browser.mathml'}) {
 5232: 	&Apache::loncommon::content_type($request,'text/xml');
 5233:     } else {
 5234: 	&Apache::loncommon::content_type($request,'text/html');
 5235:     }
 5236:     $request->send_http_header;
 5237:     return '' if $request->header_only;
 5238:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 5239:     my $url=$env{'form.url'};
 5240:     my $symb=$env{'form.symb'};
 5241:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 5242:     my $command=$commands[0];
 5243:     if ($#commands > 0) {
 5244: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 5245:     }
 5246:     if (!$url) {
 5247: 	my ($temp1,$temp2);
 5248: 	($temp1,$temp2,$env{'form.url'})=&Apache::lonnet::decode_symb($symb);
 5249: 	$url = $env{'form.url'};
 5250:     }
 5251:     &send_header($request);
 5252:     if ($url eq '' && $symb eq '' && $command eq '') {
 5253: 	if ($env{'user.adv'}) {
 5254: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 5255: 		($env{'form.codethree'})) {
 5256: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 5257: 		    $env{'form.codethree'};
 5258: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 5259: 		    &Apache::lonnet::checkin($token);
 5260: 		if ($tsymb) {
 5261: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 5262: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 5263: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
 5264: 					  ('grade_username' => $tuname,
 5265: 					   'grade_domain' => $tudom,
 5266: 					   'grade_courseid' => $tcrsid,
 5267: 					   'grade_symb' => $tsymb)));
 5268: 		    } else {
 5269: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 5270: 		    }
 5271: 		} else {
 5272: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 5273: 		}
 5274: 	    } else {
 5275: 		$request->print(&Apache::lonxml::tokeninputfield());
 5276: 	    }
 5277: 	}
 5278:     } else {
 5279: 	if (!($perm{'vgr'}=&Apache::lonnet::allowed('vgr',$env{'request.course.id'}))) {
 5280: 	    if ($perm{'vgr'}=&Apache::lonnet::allowed('vgr',$env{'request.course.id'}.'/'.$env{'request.course.sec'})) {
 5281: 		$perm{'vgr_section'}=$env{'request.course.sec'};
 5282: 	    } else {
 5283: 		delete($perm{'vgr'});
 5284: 	    }
 5285: 	}
 5286: 	if (!($perm{'mgr'}=&Apache::lonnet::allowed('mgr',$env{'request.course.id'}))) {
 5287: 	    if ($perm{'mgr'}=&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.'/'.$env{'request.course.sec'})) {
 5288: 		$perm{'mgr_section'}=$env{'request.course.sec'};
 5289: 	    } else {
 5290: 		delete($perm{'mgr'});
 5291: 	    }
 5292: 	}
 5293: 	if ($command eq 'submission' && $perm{'vgr'}) {
 5294: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 5295: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 5296: 	    &pickStudentPage($request);
 5297: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 5298: 	    &displayPage($request);
 5299: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 5300: 	    &updateGradeByPage($request);
 5301: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 5302: 	    &processGroup($request);
 5303: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 5304: 	    $request->print(&gradingmenu($request));
 5305: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 5306: 	    $request->print(&viewgrades($request));
 5307: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 5308: 	    $request->print(&processHandGrade($request));
 5309: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 5310: 	    $request->print(&editgrades($request));
 5311: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 5312: 	    $request->print(&verifyreceipt($request));
 5313: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 5314: 	    $request->print(&upcsvScores_form($request));
 5315: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 5316: 	    $request->print(&csvupload($request));
 5317: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 5318: 	    $request->print(&csvuploadmap($request));
 5319: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 5320: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 5321: 		$request->print(&csvuploadoptions($request));
 5322: 	    } else {
 5323: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 5324: 		    $env{'form.upfile_associate'} = 'reverse';
 5325: 		} else {
 5326: 		    $env{'form.upfile_associate'} = 'forward';
 5327: 		}
 5328: 		$request->print(&csvuploadmap($request));
 5329: 	    }
 5330: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 5331: 	    $request->print(&csvuploadassign($request));
 5332: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 5333: 	    $request->print(&scantron_selectphase($request));
 5334:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 5335:  	    $request->print(&scantron_do_warning($request));
 5336: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 5337: 	    $request->print(&scantron_validate_file($request));
 5338: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 5339: 	    $request->print(&scantron_process_students($request));
 5340:  	} elsif ($command eq 'scantronupload' && 
 5341:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 5342: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 5343:  	    $request->print(&scantron_upload_scantron_data($request)); 
 5344:  	} elsif ($command eq 'scantronupload_save' &&
 5345:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 5346: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 5347:  	    $request->print(&scantron_upload_scantron_data_save($request));
 5348:  	} elsif ($command eq 'scantron_download' &&
 5349: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 5350:  	    $request->print(&scantron_download_scantron_data($request));
 5351: 	} elsif ($command) {
 5352: 	    $request->print("Access Denied ($command)");
 5353: 	}
 5354:     }
 5355:     &send_footer($request);
 5356:     return '';
 5357: }
 5358: 
 5359: sub send_header {
 5360:     my ($request)= @_;
 5361:     $request->print(&Apache::lontexconvert::header());
 5362: #  $request->print("
 5363: #<script>
 5364: #remotewindow=open('','homeworkremote');
 5365: #remotewindow.close();
 5366: #</script>"); 
 5367:     $request->print(&Apache::loncommon::bodytag('Grading'));
 5368:     $request->rflush();
 5369: }
 5370: 
 5371: sub send_footer {
 5372:     my ($request)= @_;
 5373:     $request->print('</body></html>');
 5374: }
 5375: 
 5376: 1;
 5377: 
 5378: __END__;

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