File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.312: download - view: text, annotated - select for diffs
Mon Feb 13 22:11:51 2006 UTC (18 years, 8 months ago) by banghart
Branches: MAIN
CVS tags: HEAD
	Add response id to info about handback files.

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

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