File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.299: download - view: text, annotated - select for diffs
Fri Dec 2 19:20:21 2005 UTC (18 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- reset a user record should blank out fields

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

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