File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.291: download - view: text, annotated - select for diffs
Sat Oct 1 03:27:44 2005 UTC (18 years, 7 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- add the ability to limit the display of the queues and the regrade list to a specfic secion or sections

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

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