File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.145: download - view: text, annotated - select for diffs
Tue Oct 28 23:20:03 2003 UTC (20 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- implements 'graded ungraded students option' BUG#2102

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.145 2003/10/28 23:20:03 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: # 2/9,2/13 Guy Albertelli
   29: # 6/8 Gerd Kortemeyer
   30: # 7/26 H.K. Ng
   31: # 8/20 Gerd Kortemeyer
   32: # Year 2002
   33: # June-August H.K. Ng
   34: # Year 2003
   35: # February, March H.K. Ng
   36: # July, H. K. Ng
   37: #
   38: 
   39: package Apache::grades;
   40: use strict;
   41: use Apache::style;
   42: use Apache::lonxml;
   43: use Apache::lonnet;
   44: use Apache::loncommon;
   45: use Apache::lonhtmlcommon;
   46: use Apache::lonnavmaps;
   47: use Apache::lonhomework;
   48: use Apache::loncoursedata;
   49: use Apache::lonmsg qw(:user_normal_msg);
   50: use Apache::Constants qw(:common);
   51: use String::Similarity;
   52: 
   53: my %oldessays=();
   54: my %perm=();
   55: 
   56: # ----- These first few routines are general use routines.----
   57: #
   58: # --- Retrieve the parts that matches stores_\d+ from the metadata file.---
   59: sub getpartlist {
   60:     my ($url) = @_;
   61:     my @parts =();
   62:     my (@metakeys) = split(/,/,&Apache::lonnet::metadata($url,'keys'));
   63:     foreach my $key (@metakeys) {
   64: 	if ( $key =~ m/stores_(\w+)_.*/) {
   65: 	    push(@parts,$key);
   66: 	}
   67:     }
   68:     return @parts;
   69: }
   70: 
   71: # --- Get the symbolic name of a problem and the url
   72: sub get_symb_and_url {
   73:     my ($request) = @_;
   74:     (my $url=$ENV{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
   75:     my $symb=($ENV{'form.symb'} ne '' ? $ENV{'form.symb'} : (&Apache::lonnet::symbread($url)));
   76:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:$url:."); return ''; }
   77:     return ($symb,$url);
   78: }
   79: 
   80: # --- Retrieve the fullname for a user. Return lastname, first middle ---
   81: # --- Generation is attached next to the lastname if it exists. ---
   82: sub get_fullname {
   83:     my ($uname,$udom) = @_;
   84:     my %name=&Apache::lonnet::get('environment', ['lastname','generation',
   85: 						  'firstname','middlename'],
   86:                                   $udom,$uname);
   87:     my $fullname;
   88:     my ($tmp) = keys(%name);
   89:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
   90:         $fullname = &Apache::loncoursedata::ProcessFullName
   91:             (@name{qw/lastname generation firstname middlename/});
   92:     } else {
   93:         &Apache::lonnet::logthis('grades.pm: no name data for '.$uname.
   94:                                  '@'.$udom.':'.$tmp);
   95:     }
   96:     return $fullname;
   97: }
   98: 
   99: #--- Format fullname, username:domain if different for display
  100: #--- Use anywhere where the student names are listed
  101: sub nameUserString {
  102:     my ($type,$fullname,$uname,$udom) = @_;
  103:     if ($type eq 'header') {
  104: 	return '<b>&nbsp;Fullname&nbsp;</b><font color="#999999">(Username)</font>&nbsp;';
  105:     } else {
  106: 	return '&nbsp;'.$fullname.'<font color="#999999">&nbsp;('.$uname.
  107: 	    ($ENV{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</font>';
  108:     }
  109: }
  110: 
  111: #--- Get the partlist and the response type for a given problem. ---
  112: #--- Indicate if a response type is coded handgraded or not. ---
  113: sub response_type {
  114:     my ($url,$symb) = shift;
  115:     $symb=($ENV{'form.symb'} ne '' ? $ENV{'form.symb'} : (&Apache::lonnet::symbread($url))) if ($symb eq '');
  116:     my $allkeys = &Apache::lonnet::metadata($url,'keys');
  117:     my %seen = ();
  118:     my (@partlist,%handgrade);
  119:     foreach (split(/,/,&Apache::lonnet::metadata($url,'packages'))) {
  120: 	if (/^\w+response_\w+.*/) {
  121: 	    my ($responsetype,$part) = split(/_/,$_,2);
  122: 	    my ($partid,$respid) = split(/_/,$part);
  123: 	    $responsetype =~ s/response$//; # make it compatible w/ navmaps - should move to that!!
  124: 	    my ($value) = &Apache::lonnet::EXT('resource.'.$part.'.handgrade',$symb);
  125: 	    $handgrade{$part} = $responsetype.':'.($value eq 'yes' ? 'yes' : 'no'); 
  126: 	    next if ($seen{$partid} > 0);
  127: 	    $seen{$partid}++;
  128: 	    push @partlist,$partid;
  129: 	}
  130:     }
  131:     return \@partlist,\%handgrade;
  132: }
  133: 
  134: #--- Show resource title
  135: #--- and parts and response type
  136: sub showResourceInfo {
  137:     my ($url,$probTitle) = @_;
  138:     my $result ='<table border="0">'.
  139: 	'<tr><td colspan=3><font size=+1><b>Current Resource: </b>'.$probTitle.'</font></td></tr>'."\n";
  140:     my ($partlist,$handgrade) = &response_type($url);
  141:     my %resptype = ();
  142:     my $hdgrade='no';
  143:     for (sort keys(%$handgrade)) {
  144: 	my ($responsetype,$handgrade)=split(/:/,$$handgrade{$_});
  145: 	my $partID = (split(/_/))[0];
  146: 	$resptype{$partID} = $responsetype;
  147: 	$hdgrade = $handgrade if ($handgrade eq 'yes');
  148: 	$result.='<tr><td><b>Part </b>'.$partID.'</td>'.
  149: 	    '<td><b>Type: </b>'.$responsetype.'</td></tr>';
  150: #	    '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
  151:     }
  152:     $result.='</table>'."\n";
  153:     return $result,\%resptype,$hdgrade,$partlist,$handgrade;
  154: }
  155: 
  156: #--- Clean response type for display
  157: #--- Currently filters option response type only.
  158: sub cleanRecord {
  159:     my ($answer,$response,$symb) = @_;
  160:     if ($response eq 'option') {
  161: 	my (@IDs,@ans);
  162: 	foreach (split(/\&/,&Apache::lonnet::unescape($answer))) {
  163: 	    my ($optionID,$ans) = split(/=/);
  164: 	    push @IDs,$optionID.'</font>';
  165: 	    push @ans,$ans;
  166: 	}
  167: 	my $grayFont = '<font color="#999999">';
  168: 	return '<blockquote><table border="1">'.
  169: 	    '<tr valign="top"><td>Answer</td><td>'.
  170: 	    (join '</td><td>',@ans).'</td></tr>'.
  171: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</font></td><td>'.$grayFont.
  172: 	    (join '</td><td>'.$grayFont,@IDs).'</font></td></tr>'.
  173: 	    '</table></blockquote>';
  174:     }
  175:     if ($response eq 'essay') {
  176: 	if (! exists ($ENV{'form.'.$symb})) {
  177: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  178: 						  $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
  179: 						  $ENV{'course.'.$ENV{'request.course.id'}.'.num'});
  180: 
  181: 	    my $loginuser = $ENV{'user.name'}.':'.$ENV{'user.domain'};
  182: 	    $ENV{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  183: 	    $ENV{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  184: 	    $ENV{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  185: 	    $ENV{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  186: 	    $ENV{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  187: 	}
  188: 	return '<br /><br /><blockquote><pre>'.&keywords_highlight($answer).'</pre></blockquote>';
  189:     }
  190:     return $answer;
  191: }
  192: 
  193: #-- A couple of common js functions
  194: sub commonJSfunctions {
  195:     my $request = shift;
  196:     $request->print(<<COMMONJSFUNCTIONS);
  197: <script type="text/javascript" language="javascript">
  198:     function radioSelection(radioButton) {
  199: 	var selection=null;
  200: 	if (radioButton.length > 1) {
  201: 	    for (var i=0; i<radioButton.length; i++) {
  202: 		if (radioButton[i].checked) {
  203: 		    return radioButton[i].value;
  204: 		}
  205: 	    }
  206: 	} else {
  207: 	    if (radioButton.checked) return radioButton.value;
  208: 	}
  209: 	return selection;
  210:     }
  211: 
  212:     function pullDownSelection(selectOne) {
  213: 	var selection="";
  214: 	if (selectOne.length > 1) {
  215: 	    for (var i=0; i<selectOne.length; i++) {
  216: 		if (selectOne[i].selected) {
  217: 		    return selectOne[i].value;
  218: 		}
  219: 	    }
  220: 	} else {
  221:             // only one value it must be the selected one
  222: 	    return selectOne.value;
  223: 	}
  224:     }
  225: </script>
  226: COMMONJSFUNCTIONS
  227: }
  228: 
  229: #--- Dumps the class list with usernames,list of sections,
  230: #--- section, ids and fullnames for each user.
  231: sub getclasslist {
  232:     my ($getsec,$filterlist) = @_;
  233:     $getsec = $getsec eq '' ? 'all' : $getsec;
  234:     my $classlist=&Apache::loncoursedata::get_classlist();
  235:     # Bail out if we were unable to get the classlist
  236:     return if (! defined($classlist));
  237:     #
  238:     my %sections;
  239:     my %fullnames;
  240:     foreach (keys(%$classlist)) {
  241:         # the following undefs are for 'domain', and 'username' respectively.
  242: 	my (undef,undef,$end,$start,$id,$section,$fullname,$status)=
  243:             @{$classlist->{$_}};
  244: 	# filter students according to status selected
  245: 	if ($filterlist && $ENV{'form.Status'} ne 'Any') {
  246: 	    if ($ENV{'form.Status'} ne $status) {
  247: 		delete ($classlist->{$_});
  248: 		next;
  249: 	    }
  250: 	}
  251: 	$section = ($section ne '' ? $section : 'no');
  252: 	if (&canview($section)) {
  253: 	    if ($getsec eq 'all' || $getsec eq $section) {
  254: 		$sections{$section}++;
  255: 		$fullnames{$_}=$fullname;
  256: 	    } else {
  257: 		delete($classlist->{$_});
  258: 	    }
  259: 	} else {
  260: 	    delete($classlist->{$_});
  261: 	}
  262:     }
  263:     my %seen = ();
  264:     my @sections = sort(keys(%sections));
  265:     return ($classlist,\@sections,\%fullnames);
  266: }
  267: 
  268: sub canmodify {
  269:     my ($sec)=@_;
  270:     if ($perm{'mgr'}) {
  271: 	if (!defined($perm{'mgr_section'})) {
  272: 	    # can modify whole class
  273: 	    return 1;
  274: 	} else {
  275: 	    if ($sec eq $perm{'mgr_section'}) {
  276: 		#can modify the requested section
  277: 		return 1;
  278: 	    } else {
  279: 		# can't modify the request section
  280: 		return 0;
  281: 	    }
  282: 	}
  283:     }
  284:     #can't modify
  285:     return 0;
  286: }
  287: 
  288: sub canview {
  289:     my ($sec)=@_;
  290:     if ($perm{'vgr'}) {
  291: 	if (!defined($perm{'vgr_section'})) {
  292: 	    # can modify whole class
  293: 	    return 1;
  294: 	} else {
  295: 	    if ($sec eq $perm{'vgr_section'}) {
  296: 		#can modify the requested section
  297: 		return 1;
  298: 	    } else {
  299: 		# can't modify the request section
  300: 		return 0;
  301: 	    }
  302: 	}
  303:     }
  304:     #can't modify
  305:     return 0;
  306: }
  307: 
  308: #--- Retrieve the grade status of a student for all the parts
  309: sub student_gradeStatus {
  310:     my ($url,$symb,$udom,$uname,$partlist) = @_;
  311:     my %record     = &Apache::lonnet::restore($symb,$ENV{'request.course.id'},$udom,$uname);
  312:     my %partstatus = ();
  313:     foreach (@$partlist) {
  314: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  315: 	$status              = 'nothing' if ($status eq '');
  316: 	$partstatus{$_}      = $status;
  317: 	my $subkey           = "resource.$_.submitted_by";
  318: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  319:     }
  320:     return %partstatus;
  321: }
  322: 
  323: # hidden form and javascript that calls the form
  324: # Use by verifyscript and viewgrades
  325: # Shows a student's view of problem and submission
  326: sub jscriptNform {
  327:     my ($url,$symb) = @_;
  328:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  329: 	'    function viewOneStudent(user,domain) {'."\n".
  330: 	'	document.onestudent.student.value = user;'."\n".
  331: 	'	document.onestudent.userdom.value = domain;'."\n".
  332: 	'	document.onestudent.submit();'."\n".
  333: 	'    }'."\n".
  334: 	'</script>'."\n";
  335:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  336: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
  337: 	'<input type="hidden" name="url"     value="'.$url.'" />'."\n".
  338: 	'<input type="hidden" name="saveState" value="'.$ENV{'form.saveState'}.'" />'."\n".
  339: 	'<input type="hidden" name="probTitle" value="'.$ENV{'form.probTitle'}.'" />'."\n".
  340: 	'<input type="hidden" name="Status"  value="'.$ENV{'form.Status'}.'" />'."\n".
  341: 	'<input type="hidden" name="command" value="submission" />'."\n".
  342: 	'<input type="hidden" name="student" value="" />'."\n".
  343: 	'<input type="hidden" name="userdom" value="" />'."\n".
  344: 	'</form>'."\n";
  345:     return $jscript;
  346: }
  347: 
  348: #------------------ End of general use routines --------------------
  349: 
  350: #
  351: # Find most similar essay
  352: #
  353: 
  354: sub most_similar {
  355:     my ($uname,$udom,$uessay)=@_;
  356: 
  357: # ignore spaces and punctuation
  358: 
  359:     $uessay=~s/\W+/ /gs;
  360: 
  361: # these will be returned. Do not care if not at least 50 percent similar
  362:     my $limit=0.6;
  363:     my $sname='';
  364:     my $sdom='';
  365:     my $scrsid='';
  366:     my $sessay='';
  367: # go through all essays ...
  368:     foreach my $tkey (keys %oldessays) {
  369: 	my ($tname,$tdom,$tcrsid)=split(/\./,$tkey);
  370: # ... except the same student
  371:         if (($tname ne $uname) || ($tdom ne $udom)) {
  372: 	    my $tessay=$oldessays{$tkey};
  373:             $tessay=~s/\W+/ /gs;
  374: # String similarity gives up if not even limit
  375:             my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  376: # Found one
  377:             if ($tsimilar>$limit) {
  378: 		$limit=$tsimilar;
  379:                 $sname=$tname;
  380:                 $sdom=$tdom;
  381:                 $scrsid=$tcrsid;
  382:                 $sessay=$oldessays{$tkey};
  383:             }
  384:         } 
  385:     }
  386:     if ($limit>0.6) {
  387:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  388:     } else {
  389:        return ('','','','',0);
  390:     }
  391: }
  392: 
  393: #-------------------------------------------------------------------
  394: 
  395: #------------------------------------ Receipt Verification Routines
  396: #
  397: #--- Check whether a receipt number is valid.---
  398: sub verifyreceipt {
  399:     my $request  = shift;
  400: 
  401:     my $courseid = $ENV{'request.course.id'};
  402:     my $receipt  = unpack("%32C*",$Apache::lonnet::perlvar{'lonHostID'}).'-'.
  403: 	$ENV{'form.receipt'};
  404:     $receipt     =~ s/[^\-\d]//g;
  405:     my $url      = $ENV{'form.url'};
  406:     my $symb     = $ENV{'form.symb'};
  407:     unless ($symb) {
  408: 	$symb    = &Apache::lonnet::symbread($url);
  409:     }
  410: 
  411:     my $title.='<h3><font color="#339933">Verifying Submission Receipt '.
  412: 	$receipt.'</h3></font>'."\n".
  413: 	'<font size=+1><b>Resource: </b>'.$ENV{'form.probTitle'}.'</font><br><br>'."\n";
  414: 
  415:     my ($string,$contents,$matches) = ('','',0);
  416:     my (undef,undef,$fullname) = &getclasslist('all','0');
  417: 
  418:     foreach (sort {lc($$fullname{$a}) cmp lc($$fullname{$b}) } keys %$fullname) {
  419: 	my ($uname,$udom)=split(/\:/);
  420: 	if ($receipt eq 
  421: 	    &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb)) {
  422: 	    $contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
  423: 		'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  424: 		'\')"; TARGET=_self>'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  425: 		'<td>&nbsp;'.$uname.'&nbsp;</td>'.
  426: 		'<td>&nbsp;'.$udom.'&nbsp;</td></tr>'."\n";
  427: 	    
  428: 	    $matches++;
  429: 	}
  430:     }
  431:     if ($matches == 0) {
  432: 	$string = $title.'No match found for the above receipt.';
  433:     } else {
  434: 	$string = &jscriptNform($url,$symb).$title.
  435: 	    'The above receipt matches the following student'.
  436: 	    ($matches <= 1 ? '.' : 's.')."\n".
  437: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
  438: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
  439: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
  440: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
  441: 	    '<td><b>&nbsp;Domain&nbsp;</b></td></tr>'."\n".
  442: 	    $contents.
  443: 	    '</table></td></tr></table>'."\n";
  444:     }
  445:     return $string.&show_grading_menu_form($symb,$url);
  446: }
  447: 
  448: #--- This is called by a number of programs.
  449: #--- Called from the Grading Menu - View/Grade an individual student
  450: #--- Also called directly when one clicks on the subm button 
  451: #    on the problem page.
  452: sub listStudents {
  453:     my ($request) = shift;
  454: 
  455:     my ($symb,$url) = &get_symb_and_url($request);
  456:     my $cdom      = $ENV{"course.$ENV{'request.course.id'}.domain"};
  457:     my $cnum      = $ENV{"course.$ENV{'request.course.id'}.num"};
  458:     my $getsec    = $ENV{'form.section'} eq '' ? 'all' : $ENV{'form.section'};
  459:     my $submitonly= $ENV{'form.submitonly'} eq '' ? 'all' : $ENV{'form.submitonly'};
  460: 
  461:     my $viewgrade = $ENV{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  462:     $ENV{'form.probTitle'} = $ENV{'form.probTitle'} eq '' ? 
  463: 	&Apache::lonnet::gettitle($symb) : $ENV{'form.probTitle'};
  464: 
  465:     my $result='<h3><font color="#339933">&nbsp;'.$viewgrade.
  466: 	' Submissions for a Student or a Group of Students</font></h3>';
  467: 
  468:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($url,$ENV{'form.probTitle'});
  469:     $result.=$table;
  470: 
  471:     $request->print(<<LISTJAVASCRIPT);
  472: <script type="text/javascript" language="javascript">
  473:     function checkSelect(checkBox) {
  474: 	var ctr=0;
  475: 	var sense="";
  476: 	if (checkBox.length > 1) {
  477: 	    for (var i=0; i<checkBox.length; i++) {
  478: 		if (checkBox[i].checked) {
  479: 		    ctr++;
  480: 		}
  481: 	    }
  482: 	    sense = "a student or group of students";
  483: 	} else {
  484: 	    if (checkBox.checked) {
  485: 		ctr = 1;
  486: 	    }
  487: 	    sense = "the student";
  488: 	}
  489: 	if (ctr == 0) {
  490: 	    alert("Please select "+sense+" before clicking on the Next button.");
  491: 	    return false;
  492: 	}
  493: 	document.gradesub.submit();
  494:     }
  495: 
  496:     function reLoadList(formname) {
  497: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  498: 	formname.command.value = 'submission';
  499: 	formname.submit();
  500:     }
  501: </script>
  502: LISTJAVASCRIPT
  503: 
  504:     &commonJSfunctions($request);
  505:     $request->print($result);
  506: 
  507:     my $checkhdgrade = ($ENV{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked' : '';
  508:     my $checklastsub = $checkhdgrade eq '' ? 'checked' : '';
  509:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'."\n".
  510: 	'&nbsp;<b>View Problem Text: </b><input type="radio" name="vProb" value="no" checked="on" /> no '."\n".
  511: 	'<input type="radio" name="vProb" value="yes" /> one student '."\n".
  512: 	'<input type="radio" name="vProb" value="all" /> all students <br />'."\n".
  513: 	'&nbsp;<b>View Answer: </b><input type="radio" name="vAns" value="no"  /> no '."\n".
  514: 	'<input type="radio" name="vAns" value="yes" /> one student '."\n".
  515: 	'<input type="radio" name="vAns" value="all" checked="on" /> all students <br />'."\n".
  516: 	'&nbsp;<b>Submissions: </b>'."\n";
  517:     if ($ENV{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  518: 	$gradeTable.='<input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only'."\n";
  519:     }
  520: 
  521:     my $saveStatus = $ENV{'form.Status'} eq '' ? 'Active' : $ENV{'form.Status'};
  522:     $ENV{'form.Status'} = $saveStatus;
  523: 
  524:     $gradeTable.='<input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only'."\n".
  525: 	'<input type="radio" name="lastSub" value="last" /> last submission & parts info'."\n".
  526: 	'<input type="radio" name="lastSub" value="datesub" /> by dates and submissions'."\n".
  527: 	'<input type="radio" name="lastSub" value="all" /> all details'."\n".
  528: 	'<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
  529: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  530: 	'<input type="hidden" name="handgrade"   value="'.$ENV{'form.handgrade'}.'" /><br />'."\n".
  531: 	'<input type="hidden" name="showgrading" value="'.$ENV{'form.showgrading'}.'" /><br />'."\n".
  532: 	'<input type="hidden" name="saveState"   value="'.$ENV{'form.saveState'}.'" />'."\n".
  533: 	'<input type="hidden" name="probTitle"   value="'.$ENV{'form.probTitle'}.'" />'."\n".
  534: 	'<input type="hidden" name="url"  value="'.$url.'" />'."\n".
  535: 	'<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
  536: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  537: 
  538:     if (exists($ENV{'form.gradingMenu'}) && exists($ENV{'form.Status'})) {
  539: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$ENV{'form.Status'}.'" />'."\n";
  540:     } else {
  541: 	$gradeTable.='<b>Student Status:</b> '.
  542: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
  543:     }
  544: 
  545:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
  546: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
  547: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
  548:     $gradeTable.='<input type="button" '."\n".
  549: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  550: 	'value="Next->" />'."\n";
  551:     $gradeTable.='<input type="checkbox" name="checkPlag" checked="on">Check For Plagiarism</input>';
  552:     my (undef, undef, $fullname) = &getclasslist($getsec,'1');  
  553:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
  554: 	'<table border="0"><tr bgcolor="#e6ffff">';
  555:     my $loop = 0;
  556:     while ($loop < 2) {
  557: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
  558: 	    '<td>'.&nameUserString('header').'</td>';
  559: 	if ($ENV{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
  560: 	    foreach (sort(@$partlist)) {
  561: 		$gradeTable.='<td><b>&nbsp;Part '.(split(/_/))[0].' Status&nbsp;</b></td>';
  562: 	    }
  563: 	}
  564: 	$loop++;
  565: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  566:     }
  567:     $gradeTable.='</tr>'."\n";
  568: 
  569:     my $ctr = 0;
  570:     foreach my $student (sort {lc($$fullname{$a}) cmp lc($$fullname{$b}) } keys %$fullname) {
  571: 	my ($uname,$udom) = split(/:/,$student);
  572: 	my %status = ();
  573: 	if ($ENV{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
  574: 	    (%status) =&student_gradeStatus($url,$symb,$udom,$uname,$partlist);
  575: 	    my $submitted = 0;
  576: 	    my $graded = 1;
  577: 	    foreach (keys(%status)) {
  578: 		$submitted = 1 if ($status{$_} ne 'nothing');
  579: 		$graded = 0 if ($status{$_} =~ /^correct/);
  580: 		my ($foo,$partid,$foo1) = split(/\./,$_);
  581: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  582: 		    $submitted = 0;
  583: 		    $gradeTable.='<input type="hidden" name="'.
  584: 			$student.':submitted_by" value="'.
  585: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
  586: 		}
  587: 	    }
  588: 	    next if (!$submitted && ($submitonly eq 'yes' || $submitonly eq 'graded'));
  589: 	    next if (!$graded && $submitonly eq 'graded');
  590: 	}
  591: 
  592: 	$ctr++;
  593: 	if ( $perm{'vgr'} eq 'F' ) {
  594: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
  595: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
  596: 		'<td align="center"><input type=checkbox name="stuinfo" value="'.
  597: 		$student.':'.$$fullname{$student}.'&nbsp;"></td>'."\n".
  598: 		'<td>'.&nameUserString(undef,$$fullname{$student},$uname,$udom).'</td>'."\n";
  599: 
  600: 	    if ($ENV{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
  601: 		foreach (sort keys(%status)) {
  602: 		    next if (/^resource.*?submitted_by$/);
  603: 		    $gradeTable.='<td align="middle">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
  604: 		}
  605: 	    }
  606: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
  607: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
  608: 	}
  609:     }
  610:     if ($ctr%2 ==1) {
  611: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
  612: 	    if ($ENV{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
  613: 		foreach (@$partlist) {
  614: 		    $gradeTable.='<td>&nbsp;</td>';
  615: 		}
  616: 	    }
  617: 	$gradeTable.='</tr>';
  618:     }
  619: 
  620:     $gradeTable.='</table></td></tr></table>'.
  621: 	'<input type="button" '.
  622: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
  623: 	'value="Next->" /></form>'."\n";
  624:     if ($ctr == 0) {
  625: 	my $num_students=(scalar(keys(%$fullname)));
  626: 	if ($num_students eq 0) {
  627: 	    $gradeTable='<br />&nbsp;<font color="red">There are no students currently enrolled.</font>';
  628: 	} else {
  629: 	    $gradeTable='<br />&nbsp;<font color="red">'.
  630: 		'No submissions found for this resource for any students. ('.$num_students.
  631: 		' checked for submissions)</font><br />';
  632: 	}
  633:     } elsif ($ctr == 1) {
  634: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
  635:     }
  636:     $gradeTable.=&show_grading_menu_form($symb,$url);
  637:     $request->print($gradeTable);
  638:     return '';
  639: }
  640: 
  641: #---- Called from the listStudents routine
  642: #     Displays the submissions for one student or a group of students
  643: sub processGroup {
  644:     my ($request)  = shift;
  645:     my $ctr        = 0;
  646:     my @stuchecked = (ref($ENV{'form.stuinfo'}) ? @{$ENV{'form.stuinfo'}}
  647: 		      : ($ENV{'form.stuinfo'}));
  648:     my $total      = scalar(@stuchecked)-1;
  649: 
  650:     foreach (@stuchecked) {
  651: 	my ($uname,$udom,$fullname) = split(/:/);
  652: 	$ENV{'form.student'}        = $uname;
  653: 	$ENV{'form.userdom'}        = $udom;
  654: 	$ENV{'form.fullname'}       = $fullname;
  655: 	&submission($request,$ctr,$total);
  656: 	$ctr++;
  657:     }
  658:     return '';
  659: }
  660: 
  661: #------------------------------------------------------------------------------------
  662: #
  663: #-------------------------- Next few routines handles grading by student, essentially
  664: #                           handles essay response type problem/part
  665: #
  666: #--- Javascript to handle the submission page functionality ---
  667: sub sub_page_js {
  668:     my $request = shift;
  669:     $request->print(<<SUBJAVASCRIPT);
  670: <script type="text/javascript" language="javascript">
  671:     function updateRadio(formname,id,weight) {
  672: 	var gradeBox = formname["GD_BOX"+id];
  673: 	var radioButton = formname["RADVAL"+id];
  674: 	var oldpts = formname["oldpts"+id].value;
  675: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
  676: 	gradeBox.value = pts;
  677: 	var resetbox = false;
  678: 	if (isNaN(pts) || pts < 0) {
  679: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
  680: 	    for (var i=0; i<radioButton.length; i++) {
  681: 		if (radioButton[i].checked) {
  682: 		    gradeBox.value = i;
  683: 		    resetbox = true;
  684: 		}
  685: 	    }
  686: 	    if (!resetbox) {
  687: 		formtextbox.value = "";
  688: 	    }
  689: 	    return;
  690: 	}
  691: 
  692: 	if (pts > weight) {
  693: 	    var resp = confirm("You entered a value ("+pts+
  694: 			       ") greater than the weight for the part. Accept?");
  695: 	    if (resp == false) {
  696: 		gradeBox.value = oldpts;
  697: 		return;
  698: 	    }
  699: 	}
  700: 
  701: 	for (var i=0; i<radioButton.length; i++) {
  702: 	    radioButton[i].checked=false;
  703: 	    if (pts == i && pts != "") {
  704: 		radioButton[i].checked=true;
  705: 	    }
  706: 	}
  707: 	updateSelect(formname,id);
  708: 	formname["stores"+id].value = "0";
  709:     }
  710: 
  711:     function writeBox(formname,id,pts) {
  712: 	var gradeBox = formname["GD_BOX"+id];
  713: 	if (checkSolved(formname,id) == 'update') {
  714: 	    gradeBox.value = pts;
  715: 	} else {
  716: 	    var oldpts = formname["oldpts"+id].value;
  717: 	    gradeBox.value = oldpts;
  718: 	    var radioButton = formname["RADVAL"+id];
  719: 	    for (var i=0; i<radioButton.length; i++) {
  720: 		radioButton[i].checked=false;
  721: 		if (i == oldpts) {
  722: 		    radioButton[i].checked=true;
  723: 		}
  724: 	    }
  725: 	}
  726: 	formname["stores"+id].value = "0";
  727: 	updateSelect(formname,id);
  728: 	return;
  729:     }
  730: 
  731:     function clearRadBox(formname,id) {
  732: 	if (checkSolved(formname,id) == 'noupdate') {
  733: 	    updateSelect(formname,id);
  734: 	    return;
  735: 	}
  736: 	gradeSelect = formname["GD_SEL"+id];
  737: 	for (var i=0; i<gradeSelect.length; i++) {
  738: 	    if (gradeSelect[i].selected) {
  739: 		var selectx=i;
  740: 	    }
  741: 	}
  742: 	var stores = formname["stores"+id];
  743: 	if (selectx == stores.value) { return };
  744: 	var gradeBox = formname["GD_BOX"+id];
  745: 	gradeBox.value = "";
  746: 	var radioButton = formname["RADVAL"+id];
  747: 	for (var i=0; i<radioButton.length; i++) {
  748: 	    radioButton[i].checked=false;
  749: 	}
  750: 	stores.value = selectx;
  751:     }
  752: 
  753:     function checkSolved(formname,id) {
  754: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
  755: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
  756: 	    if (!reply) {return "noupdate";}
  757: 	    formname.overRideScore.value = 'yes';
  758: 	}
  759: 	return "update";
  760:     }
  761: 
  762:     function updateSelect(formname,id) {
  763: 	formname["GD_SEL"+id][0].selected = true;
  764: 	return;
  765:     }
  766: 
  767: //=========== Check that a point is assigned for all the parts  ============
  768:     function checksubmit(formname,val,total,parttot) {
  769: 	formname.gradeOpt.value = val;
  770: 	if (val == "Save & Next") {
  771: 	    for (i=0;i<=total;i++) {
  772: 		for (j=0;j<parttot;j++) {
  773: 		    var partid = formname["partid"+i+"_"+j].value;
  774: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
  775: 			var points = formname["GD_BOX"+i+"_"+partid].value;
  776: 			if (points == "") {
  777: 			    var name = formname["name"+i].value;
  778: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
  779: 			    var resp = confirm("You did not assign a score for "+studentID+
  780: 					       ", part "+partid+". Continue?");
  781: 			    if (resp == false) {
  782: 				formname["GD_BOX"+i+"_"+partid].focus();
  783: 				return false;
  784: 			    }
  785: 			}
  786: 		    }
  787: 		    
  788: 		}
  789: 	    }
  790: 	    
  791: 	}
  792: 	if (val == "Grade Student") {
  793: 	    formname.showgrading.value = "yes";
  794: 	    if (formname.Status.value == "") {
  795: 		formname.Status.value = "Active";
  796: 	    }
  797: 	    formname.studentNo.value = total;
  798: 	}
  799: 	formname.submit();
  800:     }
  801: 
  802: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
  803:     function checkSubmitPage(formname,total) {
  804: 	noscore = new Array(100);
  805: 	var ptr = 0;
  806: 	for (i=1;i<total;i++) {
  807: 	    var partid = formname["q_"+i].value;
  808: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
  809: 		var points = formname["GD_BOX"+i+"_"+partid].value;
  810: 		var status = formname["solved"+i+"_"+partid].value;
  811: 		if (points == "" && status != "correct_by_student") {
  812: 		    noscore[ptr] = i;
  813: 		    ptr++;
  814: 		}
  815: 	    }
  816: 	}
  817: 	if (ptr != 0) {
  818: 	    var sense = ptr == 1 ? ": " : "s: ";
  819: 	    var prolist = "";
  820: 	    if (ptr == 1) {
  821: 		prolist = noscore[0];
  822: 	    } else {
  823: 		var i = 0;
  824: 		while (i < ptr-1) {
  825: 		    prolist += noscore[i]+", ";
  826: 		    i++;
  827: 		}
  828: 		prolist += "and "+noscore[i];
  829: 	    }
  830: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
  831: 	    if (resp == false) {
  832: 		return false;
  833: 	    }
  834: 	}
  835: 
  836: 	formname.submit();
  837:     }
  838: </script>
  839: SUBJAVASCRIPT
  840: }
  841: 
  842: #--- javascript for essay type problem --
  843: sub sub_page_kw_js {
  844:     my $request = shift;
  845:     my $iconpath = $request->dir_config('lonIconsURL');
  846:     &commonJSfunctions($request);
  847:     $request->print(<<SUBJAVASCRIPT);
  848: <script type="text/javascript" language="javascript">
  849: 
  850: //===================== Show list of keywords ====================
  851:   function keywords(formname) {
  852:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
  853:     if (nret==null) return;
  854:     formname.keywords.value = nret;
  855: 
  856:     if (formname.keywords.value != "") {
  857: 	formname.refresh.value = "on";
  858: 	formname.submit();
  859:     }
  860:     return;
  861:   }
  862: 
  863: //===================== Script to view submitted by ==================
  864:   function viewSubmitter(submitter) {
  865:     document.SCORE.refresh.value = "on";
  866:     document.SCORE.NCT.value = "1";
  867:     document.SCORE.unamedom0.value = submitter;
  868:     document.SCORE.submit();
  869:     return;
  870:   }
  871: 
  872: //===================== Script to add keyword(s) ==================
  873:   function getSel() {
  874:     if (document.getSelection) txt = document.getSelection();
  875:     else if (document.selection) txt = document.selection.createRange().text;
  876:     else return;
  877:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
  878:     if (cleantxt=="") {
  879: 	alert("Please select a word or group of words from document and then click this link.");
  880: 	return;
  881:     }
  882:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
  883:     if (nret==null) return;
  884:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
  885:     if (document.SCORE.keywords.value != "") {
  886: 	document.SCORE.refresh.value = "on";
  887: 	document.SCORE.submit();
  888:     }
  889:     return;
  890:   }
  891: 
  892: //====================== Script for composing message ==============
  893:    // preload images
  894:    img1 = new Image();
  895:    img1.src = "$iconpath/mailbkgrd.gif";
  896:    img2 = new Image();
  897:    img2.src = "$iconpath/mailto.gif";
  898: 
  899:   function msgCenter(msgform,usrctr,fullname) {
  900:     var Nmsg  = msgform.savemsgN.value;
  901:     savedMsgHeader(Nmsg,usrctr,fullname);
  902:     var subject = msgform.msgsub.value;
  903:     var msgchk = document.SCORE["includemsg"+usrctr].value;
  904:     re = /msgsub/;
  905:     var shwsel = "";
  906:     if (re.test(msgchk)) { shwsel = "checked" }
  907:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
  908:     displaySubject(checkEntities(subject),shwsel);
  909:     for (var i=1; i<=Nmsg; i++) {
  910: 	var testmsg = "savemsg"+i+",";
  911: 	re = new RegExp(testmsg,"g");
  912: 	shwsel = "";
  913: 	if (re.test(msgchk)) { shwsel = "checked" }
  914: 	var message = document.SCORE["savemsg"+i].value;
  915: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
  916: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
  917: 	                                   //any &lt; is already converted to <, etc. However, only once!!
  918:     }
  919:     newmsg = document.SCORE["newmsg"+usrctr].value;
  920:     shwsel = "";
  921:     re = /newmsg/;
  922:     if (re.test(msgchk)) { shwsel = "checked" }
  923:     newMsg(newmsg,shwsel);
  924:     msgTail(); 
  925:     return;
  926:   }
  927: 
  928:   function checkEntities(strx) {
  929:     if (strx.length == 0) return strx;
  930:     var orgStr = ["&", "<", ">", '"']; 
  931:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
  932:     var counter = 0;
  933:     while (counter < 4) {
  934: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
  935: 	counter++;
  936:     }
  937:     return strx;
  938:   }
  939: 
  940:   function strReplace(strx, orgStr, newStr) {
  941:     return strx.split(orgStr).join(newStr);
  942:   }
  943: 
  944:   function savedMsgHeader(Nmsg,usrctr,fullname) {
  945:     var height = 70*Nmsg+250;
  946:     var scrollbar = "no";
  947:     if (height > 600) {
  948: 	height = 600;
  949: 	scrollbar = "yes";
  950:     }
  951:     var xpos = (screen.width-600)/2;
  952:     xpos = (xpos < 0) ? '0' : xpos;
  953:     var ypos = (screen.height-height)/2-30;
  954:     ypos = (ypos < 0) ? '0' : ypos;
  955: 
  956:     pWin = window.open('', 'MessageCenter', 'toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
  957:     pWin.focus();
  958:     pDoc = pWin.document;
  959:     pDoc.open('text/html','replace');
  960:     pDoc.write("<html><head>");
  961:     pDoc.write("<title>Message Central</title>");
  962: 
  963:     pDoc.write("<script language=javascript>");
  964:     pDoc.write("function checkInput() {");
  965:     pDoc.write("  opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);");
  966:     pDoc.write("  var nmsg   = opener.document.SCORE.savemsgN.value;");
  967:     pDoc.write("  var usrctr = document.msgcenter.usrctr.value;");
  968:     pDoc.write("  var newval = opener.document.SCORE[\\"newmsg\\"+usrctr];");
  969:     pDoc.write("  newval.value = opener.checkEntities(document.msgcenter.newmsg.value);");
  970: 
  971:     pDoc.write("  var msgchk = \\"\\";");
  972:     pDoc.write("  if (document.msgcenter.subchk.checked) {");
  973:     pDoc.write("     msgchk = \\"msgsub,\\";");
  974:     pDoc.write("  }");
  975:     pDoc.write("  var includemsg = 0;");
  976:     pDoc.write("  for (var i=1; i<=nmsg; i++) {");
  977:     pDoc.write("      var opnmsg = opener.document.SCORE[\\"savemsg\\"+i];");
  978:     pDoc.write("      var frmmsg = document.msgcenter[\\"msg\\"+i];");
  979:     pDoc.write("      opnmsg.value = opener.checkEntities(frmmsg.value);");
  980:     pDoc.write("      var showflg = opener.document.SCORE[\\"shownOnce\\"+i];");
  981:     pDoc.write("      showflg.value = \\"1\\";");
  982:     pDoc.write("      var chkbox = document.msgcenter[\\"msgn\\"+i];");
  983:     pDoc.write("      if (chkbox.checked) {");
  984:     pDoc.write("         msgchk += \\"savemsg\\"+i+\\",\\";");
  985:     pDoc.write("         includemsg = 1;");
  986:     pDoc.write("      }");
  987:     pDoc.write("  }");
  988:     pDoc.write("  if (document.msgcenter.newmsgchk.checked) {");
  989:     pDoc.write("     msgchk += \\"newmsg\\"+usrctr;");
  990:     pDoc.write("     includemsg = 1;");
  991:     pDoc.write("  }");
  992:     pDoc.write("  imgformname = opener.document.SCORE[\\"mailicon\\"+usrctr];");
  993:     pDoc.write("  imgformname.src = \\"$iconpath/\\"+((includemsg) ? \\"mailto.gif\\" : \\"mailbkgrd.gif\\");");
  994:     pDoc.write("  var includemsg = opener.document.SCORE[\\"includemsg\\"+usrctr];");
  995:     pDoc.write("  includemsg.value = msgchk;");
  996: 
  997:     pDoc.write("  self.close()");
  998: 
  999:     pDoc.write("}");
 1000: 
 1001:     pDoc.write("<");
 1002:     pDoc.write("/script>");
 1003: 
 1004:     pDoc.write("</head><body bgcolor=white>");
 1005: 
 1006:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1007:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1008:     pDoc.write("<font color=\\"green\\" size=+1>&nbsp;Compose Message for \"+fullname+\"</font><br><br>");
 1009: 
 1010:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1011:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1012:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
 1013: }
 1014:     function displaySubject(msg,shwsel) {
 1015:     pDoc = pWin.document;
 1016:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1017:     pDoc.write("<td>Subject</td>");
 1018:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
 1019:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
 1020: }
 1021: 
 1022:   function displaySavedMsg(ctr,msg,shwsel) {
 1023:     pDoc = pWin.document;
 1024:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1025:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
 1026:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
 1027:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
 1028: }
 1029: 
 1030:   function newMsg(newmsg,shwsel) {
 1031:     pDoc = pWin.document;
 1032:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1033:     pDoc.write("<td align=\\"center\\">New</td>");
 1034:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
 1035:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
 1036: }
 1037: 
 1038:   function msgTail() {
 1039:     pDoc = pWin.document;
 1040:     pDoc.write("</table>");
 1041:     pDoc.write("</td></tr></table>&nbsp;");
 1042:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1043:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br><br>");
 1044:     pDoc.write("</form>");
 1045:     pDoc.write("</body></html>");
 1046:     pDoc.close();
 1047: }
 1048: 
 1049: //====================== Script for keyword highlight options ==============
 1050:   function kwhighlight() {
 1051:     var kwclr    = document.SCORE.kwclr.value;
 1052:     var kwsize   = document.SCORE.kwsize.value;
 1053:     var kwstyle  = document.SCORE.kwstyle.value;
 1054:     var redsel = "";
 1055:     var grnsel = "";
 1056:     var blusel = "";
 1057:     if (kwclr=="red")   {var redsel="checked"};
 1058:     if (kwclr=="green") {var grnsel="checked"};
 1059:     if (kwclr=="blue")  {var blusel="checked"};
 1060:     var sznsel = "";
 1061:     var sz1sel = "";
 1062:     var sz2sel = "";
 1063:     if (kwsize=="0")  {var sznsel="checked"};
 1064:     if (kwsize=="+1") {var sz1sel="checked"};
 1065:     if (kwsize=="+2") {var sz2sel="checked"};
 1066:     var synsel = "";
 1067:     var syisel = "";
 1068:     var sybsel = "";
 1069:     if (kwstyle=="")    {var synsel="checked"};
 1070:     if (kwstyle=="<i>") {var syisel="checked"};
 1071:     if (kwstyle=="<b>") {var sybsel="checked"};
 1072:     highlightCentral();
 1073:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1074:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1075:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1076:     highlightend();
 1077:     return;
 1078:   }
 1079: 
 1080:   function highlightCentral() {
 1081: //    if (window.hwdWin) window.hwdWin.close();
 1082:     var xpos = (screen.width-400)/2;
 1083:     xpos = (xpos < 0) ? '0' : xpos;
 1084:     var ypos = (screen.height-330)/2-30;
 1085:     ypos = (ypos < 0) ? '0' : ypos;
 1086: 
 1087:     hwdWin = window.open('', 'KeywordHighlightCentral', 'toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1088:     hwdWin.focus();
 1089:     var hDoc = hwdWin.document;
 1090:     hDoc.open('text/html','replace');
 1091:     hDoc.write("<html><head>");
 1092:     hDoc.write("<title>Highlight Central</title>");
 1093: 
 1094:     hDoc.write("<script language=javascript>");
 1095:     hDoc.write("function updateChoice(flag) {");
 1096:     hDoc.write("  opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);");
 1097:     hDoc.write("  opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);");
 1098:     hDoc.write("  opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);");
 1099:     hDoc.write("  opener.document.SCORE.refresh.value = \\"on\\";");
 1100:     hDoc.write("  if (opener.document.SCORE.keywords.value!=\\"\\"){");
 1101:     hDoc.write("     opener.document.SCORE.submit();");
 1102:     hDoc.write("  }");
 1103:     hDoc.write("  self.close()");
 1104:     hDoc.write("}");
 1105: 
 1106:     hDoc.write("<");
 1107:     hDoc.write("/script>");
 1108: 
 1109:     hDoc.write("</head><body bgcolor=white>");
 1110: 
 1111:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1112:     hDoc.write("<font color=\\"green\\" size=+1>&nbsp;Keyword Highlight Options</font><br><br>");
 1113: 
 1114:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1115:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1116:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
 1117:   }
 1118: 
 1119:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1120:     var hDoc = hwdWin.document;
 1121:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1122:     hDoc.write("<td align=\\"left\\">");
 1123:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
 1124:     hDoc.write("<td align=\\"left\\">");
 1125:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
 1126:     hDoc.write("<td align=\\"left\\">");
 1127:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
 1128:     hDoc.write("</tr>");
 1129:   }
 1130: 
 1131:   function highlightend() { 
 1132:     var hDoc = hwdWin.document;
 1133:     hDoc.write("</table>");
 1134:     hDoc.write("</td></tr></table>&nbsp;");
 1135:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1136:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br><br>");
 1137:     hDoc.write("</form>");
 1138:     hDoc.write("</body></html>");
 1139:     hDoc.close();
 1140:   }
 1141: 
 1142: </script>
 1143: SUBJAVASCRIPT
 1144: }
 1145: 
 1146: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1147: sub gradeBox {
 1148:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1149: 
 1150:     my $checkIcon = '<img src="'.$request->dir_config('lonIconsURL').
 1151: 	'/check.gif" height="16" border="0" />';
 1152: 
 1153:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1154:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
 1155: 		  '<font color="red">problem weight assigned by computer</font>');
 1156:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1157:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1158: 		  '' : $$record{'resource.'.$partid.'.awarded'}*$wgt);
 1159:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1160: 
 1161:     $result.='<table border="0"><tr><td>'.
 1162: 	'<b>Part </b>'.$partid.' <b>Points: </b></td><td>'."\n";
 1163: 
 1164:     my $ctr = 0;
 1165:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1166:     while ($ctr<=$wgt) {
 1167: 	$result.= '<td><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1168: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1169: 	    $ctr.')" value="'.$ctr.'" '.
 1170: 	    ($score eq $ctr ? 'checked':'').' /> '.$ctr."</td>\n";
 1171: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1172: 	$ctr++;
 1173:     }
 1174:     $result.='</tr></table>';
 1175: 
 1176:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
 1177:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1178: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1179: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1180: 	$wgt.')" /></td>'."\n";
 1181:     $result.='<td>/'.$wgt.' '.$wgtmsg.
 1182: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1183: 	' </td><td>'."\n";
 1184: 
 1185:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1186: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1187:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1188: 	$result.='<option> </option>'.
 1189: 	    '<option selected="on">excused</option>';
 1190:     } else {
 1191: 	$result.='<option selected="on"> </option>'.
 1192: 	    '<option>excused</option>';
 1193:     }
 1194:     $result.='<option>reset status</option></select>'."\n";
 1195:     $result.="&nbsp&nbsp\n";
 1196:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1197: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1198: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1199: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n";
 1200:     $result.='</td></tr></table>'."\n";
 1201:     return $result;
 1202: }
 1203: 
 1204: sub show_problem {
 1205:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode) = @_;
 1206:     my $rendered;
 1207:     if ($mode eq 'both' or $mode eq 'text') {
 1208: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1209: 					     $ENV{'request.course.id'});
 1210:     }
 1211:     if ($removeform) {
 1212: 	$rendered=~s|<form(.*?)>||g;
 1213: 	$rendered=~s|</form>||g;
 1214: 	$rendered=~s|name="submit"|name="would_have_been_submit"|g;
 1215:     }
 1216:     my $companswer;
 1217:     if ($mode eq 'both' or $mode eq 'answer') {
 1218: 	$companswer=&Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1219: 						    $ENV{'request.course.id'});
 1220:     }
 1221:     if ($removeform) {
 1222: 	$companswer=~s|<form(.*?)>||g;
 1223: 	$companswer=~s|</form>||g;
 1224: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1225:     }
 1226:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
 1227:     $result.='<table border="0" width="100%">';
 1228:     if ($viewon) {
 1229: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
 1230: 	if ($mode eq 'both' or $mode eq 'text') {
 1231: 	    $result.='View of the problem - ';
 1232: 	} else {
 1233: 	    $result.='Correct answer: ';
 1234: 	}
 1235: 	$result.=$ENV{'form.fullname'}.'</b></td></tr>';
 1236:     }
 1237:     if ($mode eq 'both') {
 1238: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
 1239: 	$result.='<b>Correct answer:</b><br />'.$companswer;
 1240:     } elsif ($mode eq 'text') {
 1241: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
 1242:     } elsif ($mode eq 'answer') {
 1243: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
 1244:     }
 1245:     $result.='</td></tr></table>';
 1246:     $result.='</td></tr></table><br />';
 1247:     return $result;
 1248: }
 1249: 
 1250: # --------------------------- show submissions of a student, option to grade 
 1251: sub submission {
 1252:     my ($request,$counter,$total) = @_;
 1253: 
 1254:     (my $url=$ENV{'form.url'})=~s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
 1255:     my ($uname,$udom)     = ($ENV{'form.student'},$ENV{'form.userdom'});
 1256:     $udom = ($udom eq '' ? $ENV{'user.domain'} : $udom); #has form.userdom changed for a student?
 1257:     my $usec = &Apache::lonnet::getsection($udom,$uname,$ENV{'request.course.id'});
 1258:     $ENV{'form.fullname'} = &get_fullname ($uname,$udom) if $ENV{'form.fullname'} eq '';
 1259: 
 1260:     my $symb=($ENV{'form.symb'} ne '' ? $ENV{'form.symb'} : (&Apache::lonnet::symbread($url)));
 1261:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:$url:."); return ''; }
 1262: 
 1263:     if (!&canview($usec)) {
 1264: 	$request->print('<font color="red">Unable to view requested student.('.
 1265: 			$uname.$udom.$usec.$ENV{'request.course.id'}.')</font>');
 1266: 	$request->print(&show_grading_menu_form($symb,$url));
 1267: 	return;
 1268:     }
 1269: 
 1270:     $ENV{'form.lastSub'} = ($ENV{'form.lastSub'} eq '' ? 'datesub' : $ENV{'form.lastSub'});
 1271:     my $last = ($ENV{'form.lastSub'} eq 'last' ? 'last' : '');
 1272:     my $checkIcon = '<img src="'.$request->dir_config('lonIconsURL').
 1273: 	'/check.gif" height="16" border="0" />';
 1274: 
 1275:     # header info
 1276:     if ($counter == 0) {
 1277: 	&sub_page_js($request);
 1278: 	&sub_page_kw_js($request) if ($ENV{'form.handgrade'} eq 'yes');
 1279: 	$ENV{'form.probTitle'} = $ENV{'form.probTitle'} eq '' ? 
 1280: 	    &Apache::lonnet::gettitle($symb) : $ENV{'form.probTitle'};
 1281: 
 1282: 	$request->print('<h3>&nbsp;<font color="#339933">Submission Record</font></h3>'."\n".
 1283: 			'<font size=+1>&nbsp;<b>Resource: </b>'.$ENV{'form.probTitle'}.'</font>'."\n");
 1284: 
 1285: 	if ($ENV{'form.handgrade'} eq 'no') {
 1286: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
 1287: 		$checkIcon.' symbol.'."\n";
 1288: 	    $request->print($checkMark);
 1289: 	}
 1290: 
 1291: 	# option to display problem, only once else it cause problems 
 1292:         # with the form later since the problem has a form.
 1293: 	if ($ENV{'form.vProb'} eq 'yes' or $ENV{'form.vAns'} eq 'yes') {
 1294: 	    my $mode;
 1295: 	    if ($ENV{'form.vProb'} eq 'yes' && $ENV{'form.vAns'} eq 'yes') {
 1296: 		$mode='both';
 1297: 	    } elsif ($ENV{'form.vProb'} eq 'yes') {
 1298: 		$mode='text';
 1299: 	    } elsif ($ENV{'form.vAns'} eq 'yes') {
 1300: 		$mode='answer';
 1301: 	    }
 1302: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1303: 	}
 1304: 	
 1305: 	# kwclr is the only variable that is guaranteed to be non blank 
 1306:         # if this subroutine has been called once.
 1307: 	my %keyhash = ();
 1308: 	if ($ENV{'form.kwclr'} eq '' && $ENV{'form.handgrade'} eq 'yes') {
 1309: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1310: 					     $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
 1311: 					     $ENV{'course.'.$ENV{'request.course.id'}.'.num'});
 1312: 
 1313: 	    my $loginuser = $ENV{'user.name'}.':'.$ENV{'user.domain'};
 1314: 	    $ENV{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1315: 	    $ENV{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1316: 	    $ENV{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1317: 	    $ENV{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1318: 	    $ENV{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1319: 		$keyhash{$symb.'_subject'} : $ENV{'form.probTitle'};
 1320: 	    $ENV{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1321: 	}
 1322: 	my $overRideScore = $ENV{'form.overRideScore'} eq '' ? 'no' : $ENV{'form.overRideScore'};
 1323: 
 1324: 	$request->print('<form action="/adm/grades" method="post" name="SCORE">'."\n".
 1325: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1326: 			'<input type="hidden" name="saveState"  value="'.$ENV{'form.saveState'}.'" />'."\n".
 1327: 			'<input type="hidden" name="Status"     value="'.$ENV{'form.Status'}.'" />'."\n".
 1328: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1329: 			'<input type="hidden" name="probTitle"  value="'.$ENV{'form.probTitle'}.'" />'."\n".
 1330: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1331: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1332: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1333: 			'<input type="hidden" name="symb"       value="'.$symb.'" />'."\n".
 1334: 			'<input type="hidden" name="url"        value="'.$url.'" />'."\n".
 1335: 			'<input type="hidden" name="showgrading" value="'.$ENV{'form.showgrading'}.'" />'."\n".
 1336: 			'<input type="hidden" name="vProb"      value="'.$ENV{'form.vProb'}.'" />'."\n".
 1337: 			'<input type="hidden" name="vAns"       value="'.$ENV{'form.vAns'}.'" />'."\n".
 1338: 			'<input type="hidden" name="lastSub"    value="'.$ENV{'form.lastSub'}.'" />'."\n".
 1339: 			'<input type="hidden" name="section"    value="'.$ENV{'form.section'}.'">'."\n".
 1340: 			'<input type="hidden" name="submitonly" value="'.$ENV{'form.submitonly'}.'">'."\n".
 1341: 			'<input type="hidden" name="handgrade"  value="'.$ENV{'form.handgrade'}.'">'."\n".
 1342: 			'<input type="hidden" name="NCT"'.
 1343: 			' value="'.($ENV{'form.NTSTU'} ne '' ? $ENV{'form.NTSTU'} : $total+1).'" />'."\n");
 1344: 	if ($ENV{'form.handgrade'} eq 'yes') {
 1345: 	    $request->print('<input type="hidden" name="keywords" value="'.$ENV{'form.keywords'}.'" />'."\n".
 1346: 			    '<input type="hidden" name="kwclr"    value="'.$ENV{'form.kwclr'}.'" />'."\n".
 1347: 			    '<input type="hidden" name="kwsize"   value="'.$ENV{'form.kwsize'}.'" />'."\n".
 1348: 			    '<input type="hidden" name="kwstyle"  value="'.$ENV{'form.kwstyle'}.'" />'."\n".
 1349: 			    '<input type="hidden" name="msgsub"   value="'.$ENV{'form.msgsub'}.'" />'."\n".
 1350: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1351: 			    '<input type="hidden" name="savemsgN" value="'.$ENV{'form.savemsgN'}.'" />'."\n");
 1352: 	}
 1353: 	
 1354: 	my ($cts,$prnmsg) = (1,'');
 1355: 	while ($cts <= $ENV{'form.savemsgN'}) {
 1356: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1357: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1358: 		 &Apache::lonfeedback::clear_out_html($ENV{'form.savemsg'.$cts}) :
 1359: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1360: 		'" />'."\n".
 1361: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1362: 	    $cts++;
 1363: 	}
 1364: 	$request->print($prnmsg);
 1365: 
 1366: 	if ($ENV{'form.handgrade'} eq 'yes' && $ENV{'form.showgrading'} eq 'yes') {
 1367: #
 1368: # Print out the keyword options line
 1369: #
 1370: 	    $request->print(<<KEYWORDS);
 1371: &nbsp;<b>Keyword Options:</b>&nbsp;
 1372: <a href="javascript:keywords(document.SCORE)"; TARGET=_self>List</a>&nbsp; &nbsp;
 1373: <a href="#" onMouseDown="javascript:getSel(); return false"
 1374:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 1375: <a href="javascript:kwhighlight()"; TARGET=_self>Highlight Attribute</a><br /><br />
 1376: KEYWORDS
 1377: #
 1378: # Load the other essays for similarity check
 1379: #
 1380:             my $essayurl=&Apache::lonnet::declutter($url);
 1381: 	    my ($adom,$aname,$apath)=($essayurl=~/^(\w+)\/(\w+)\/(.*)$/);
 1382: 	    $apath=&Apache::lonnet::escape($apath);
 1383: 	    $apath=~s/\W/\_/gs;
 1384: 	    %oldessays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 1385:         }
 1386:     }
 1387: 
 1388:     if ($ENV{'form.vProb'} eq 'all' or $ENV{'form.vAns'} eq 'all') {
 1389: 	$request->print('<br /><br /><br />') if ($counter > 0);
 1390: 	my $mode;
 1391: 	if ($ENV{'form.vProb'} eq 'all' && $ENV{'form.vAns'} eq 'all') {
 1392: 	    $mode='both';
 1393: 	} elsif ($ENV{'form.vProb'} eq 'all' ) {
 1394: 	    $mode='text';
 1395: 	} elsif ($ENV{'form.vAns'} eq 'all') {
 1396: 	    $mode='answer';
 1397: 	}
 1398: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
 1399:     }
 1400: 
 1401:     my %record = &Apache::lonnet::restore($symb,$ENV{'request.course.id'},$udom,$uname);
 1402: 
 1403:     my ($partlist,$handgrade) = &response_type($url,$symb);
 1404: 
 1405:     # Display student info
 1406:     $request->print(($counter == 0 ? '' : '<br />'));
 1407:     my $result='<table border="0" width=100%><tr><td bgcolor="#777777">'."\n".
 1408: 	'<table border="0" width=100%><tr bgcolor="#edffff"><td>'."\n";
 1409: 
 1410:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$ENV{'form.fullname'},$uname,$udom).'<br />'."\n";
 1411:     $result.='<input type="hidden" name="name'.$counter.
 1412: 	'" value="'.$ENV{'form.fullname'}.'" />'."\n";
 1413: 
 1414:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 1415:     my @col_fullnames;
 1416:     my ($classlist,$fullname);
 1417:     if ($ENV{'form.handgrade'} eq 'yes') {
 1418: 	($classlist,undef,$fullname) = &getclasslist('all','0');
 1419: 	for (keys (%$handgrade)) {
 1420: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
 1421: 					    '.maxcollaborators',
 1422:                                             $symb,$udom,$uname);
 1423: 	    next if ($ncol <= 0);
 1424:             s/\_/\./g;
 1425:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
 1426:             my @goodcollaborators = ();
 1427:             my @badcollaborators  = ();
 1428: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
 1429: 		$_ =~ s/[\$\^\(\)]//g;
 1430: 		next if ($_ eq '');
 1431: 		my ($co_name,$co_dom) = split /\@|:/,$_;
 1432: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 1433: 		next if ($co_name eq $uname && $co_dom eq $udom);
 1434: 		# Doing this grep allows 'fuzzy' specification
 1435: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
 1436: 		if (! scalar(@Matches)) {
 1437: 		    push @badcollaborators,$_;
 1438: 		} else {
 1439: 		    push @goodcollaborators, @Matches;
 1440: 		}
 1441: 	    }
 1442:             if (scalar(@goodcollaborators) != 0) {
 1443:                 $result.='<b>Collaborators: </b>';
 1444:                 foreach (@goodcollaborators) {
 1445: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
 1446: 		    push @col_fullnames, $givenn.' '.$lastname;
 1447: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
 1448: 		}
 1449:                 $result.='<br />'."\n";
 1450: 		$result.='<input type="hidden" name="collaborator'.$counter.
 1451: 		    '" value="'.(join ':',@goodcollaborators).'" />'."\n";
 1452: 	    }
 1453: 	    if (scalar(@badcollaborators) > 0) {
 1454: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
 1455: 		$result.='This student has submitted ';
 1456: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
 1457: 		$result .= ': '.join(', ',@badcollaborators);
 1458: 		$result .= '</td></tr></table>';
 1459: 	    }         
 1460: 	    if (scalar(@badcollaborators > $ncol)) {
 1461: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
 1462: 		$result .= 'This student has submitted too many '.
 1463: 		    'collaborators.  Maximum is '.$ncol.'.';
 1464: 		$result .= '</td></tr></table>';
 1465: 	    }
 1466: 	}
 1467:     }
 1468:     $request->print($result."\n");
 1469: 
 1470:     # print student answer/submission
 1471:     # Options are (1) Handgaded submission only
 1472:     #             (2) Last submission, includes submission that is not handgraded 
 1473:     #                  (for multi-response type part)
 1474:     #             (3) Last submission plus the parts info
 1475:     #             (4) The whole record for this student
 1476:     if ($ENV{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 1477: 	if ($ENV{'form.'.$uname.':'.$udom.':submitted_by'}) {
 1478: 	    my $submitby=''.
 1479: 		'<b>Collaborative submission by: </b>'.
 1480: 		'<a href="javascript:viewSubmitter(\''.
 1481: 		$ENV{'form.'.$uname.':'.$udom.':submitted_by'}.
 1482: 		'\')"; TARGET=_self>'.
 1483: 		$$fullname{$ENV{'form.'.$uname.':'.$udom.':submitted_by'}}.'</a>';
 1484: 	    $request->print($submitby);
 1485: 	} else {
 1486: 	    my ($string,$timestamp)= &get_last_submission (\%record);
 1487: 	    my $lastsubonly=''.
 1488: 		($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
 1489: 		 $$timestamp)."</td></tr>\n";
 1490: 	    if ($$timestamp eq '') {
 1491: 		$lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
 1492: 	    } else {
 1493: 		for my $part (sort keys(%$handgrade)) {
 1494: 		    my ($responsetype,$foo) = split(/:/,$$handgrade{$part});
 1495: 		    my ($partid,$respid) = split(/_/,$part);
 1496: 		    if (!exists($record{'resource.'.$partid.'.'.$respid.'.submission'})) {
 1497: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part '.
 1498: 			    $partid.'</b> <font color="#999999">( ID '.$respid.
 1499: 			    ' )</font>&nbsp; &nbsp;'.
 1500: 			    '<font color="red">Nothing submitted - no attempts</font><br /><br />';
 1501:  		    } else {
 1502: 			foreach (@$string) {
 1503: 			    my ($partid,$respid) = /^resource\.(\w+)\.(\w+)\.submission/;
 1504: 			    if ($part eq ($partid.'_'.$respid)) {
 1505: 				my ($ressub,$subval) = split(/:/,$_,2);
 1506:                             # Similarity check
 1507: 				my $similar='';
 1508: 				my $oname;
 1509: 				my $odom;
 1510: 				my $ocrsid;
 1511: 				my $oessay;
 1512: 				my $osim;
 1513: 				if($ENV{'form.checkPlag'}){
 1514: 				    ($oname,$odom,$ocrsid,$oessay,$osim)=&most_similar($uname,$udom,$subval);
 1515: 				    if ($osim) {
 1516: 					$osim=int($osim*100.0);
 1517: 					$similar='<hr /><h3><font color="#FF0000">Essay is '.$osim.
 1518: 					    '% similar to an essay by '.&Apache::loncommon::plainname($oname,$odom).
 1519: 					    '</font></h3><blockquote><i>'.
 1520: 					    &keywords_highlight($oessay).'</i></blockquote><hr />';
 1521: 				    }
 1522: 				}
 1523: 				$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part '.
 1524: 				    $partid.'</b> <font color="#999999">( ID '.$respid.
 1525: 				    ' )</font>&nbsp; &nbsp;'.
 1526: 				    ($record{"resource.$partid.$respid.uploadedurl"}?
 1527: 				     '<a href="'.
 1528: 				     &Apache::lonnet::tokenwrapper($record{"resource.$partid.$respid.uploadedurl"}).
 1529: 				     '"><img src="/adm/lonIcons/unknown.gif" border=0"> File uploaded by student</a> '.
 1530: 				     '<font color="red" size="1">Like all files provided by users, '.
 1531: 				     'this file may contain virusses</font><br />':'').
 1532: 				     '<b>Submitted Answer: </b>'.
 1533: 				     &cleanRecord($subval,$responsetype,$symb).
 1534: 				     '<br /><br />'.$similar."\n"
 1535: 				     if ($ENV{'form.lastSub'} eq 'lastonly' || 
 1536: 					 ($ENV{'form.lastSub'} eq 'hdgrade' && 
 1537: 					  $$handgrade{$part} =~ /:yes$/));
 1538: 			    }
 1539: 			}
 1540: 		    }
 1541: 		}
 1542: 	    }
 1543: 	    $lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
 1544: 	    $request->print($lastsubonly);
 1545: 	}
 1546:     } elsif ($ENV{'form.lastSub'} eq 'datesub') {
 1547: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($url);
 1548: 	$request->print(&displaySubByDates(\$symb,\%record,$parts,$responseType,$checkIcon));
 1549:     } elsif ($ENV{'form.lastSub'} =~ /^(last|all)$/) {
 1550: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 1551: 								 $ENV{'request.course.id'},
 1552: 								 $last,'.submission',
 1553: 								 'Apache::grades::keywords_highlight'));
 1554:     }
 1555: 
 1556:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 1557: 	.$udom.'" />'."\n");
 1558:     
 1559:     # return if view submission with no grading option
 1560:     if ($ENV{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 1561: 	my $toGrade.='<input type="button" value="Grade Student" '.
 1562: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 1563: 	    .$counter.'\');" TARGET=_self> &nbsp;'."\n" if (&canmodify($usec));
 1564: 	$toGrade.='</td></tr></table></td></tr></table></form>'."\n";
 1565: 	$toGrade.=&show_grading_menu_form($symb,$url) 
 1566: 	    if (($ENV{'form.command'} eq 'submission') || 
 1567: 		($ENV{'form.command'} eq 'processGroup' && $counter == $total));
 1568: 	$request = print($toGrade);
 1569: 	return;
 1570:     }
 1571: 
 1572:     # essay grading message center
 1573:     if ($ENV{'form.handgrade'} eq 'yes') {
 1574: 	my ($lastname,$givenn) = split(/,/,$ENV{'form.fullname'});
 1575: 	my $msgfor = $givenn.' '.$lastname;
 1576: 	if (scalar(@col_fullnames) > 0) {
 1577: 	    my $lastone = pop @col_fullnames;
 1578: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
 1579: 	}
 1580: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 1581: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 1582: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 1583: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 1584: 	    ',\''.$msgfor.'\')"; TARGET=_self>'.
 1585: 	    'Compose Message to student'.(scalar(@col_fullnames) >= 1 ? 's' : '').'</a> &nbsp;'.
 1586: 	    '<img src="'.$request->dir_config('lonIconsURL').
 1587: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 1588: 	    '<br />&nbsp;(Message will be sent when you click on Save & Next below.)'."\n" 
 1589: 	    if ($ENV{'form.handgrade'} eq 'yes');
 1590: 	$request->print($result);
 1591:     }
 1592: 
 1593:     my %seen = ();
 1594:     my @partlist;
 1595:     my @gradePartRespid;
 1596:     for (sort keys(%$handgrade)) {
 1597: 	my ($partid,$respid) = split(/_/);
 1598: 	next if ($seen{$partid} > 0);
 1599: 	$seen{$partid}++;
 1600: 	next if ($$handgrade{$_} =~ /:no$/ && $ENV{'form.lastSub'} =~ /^(hdgrade)$/);
 1601: 	push @partlist,$partid;
 1602: 	push @gradePartRespid,$partid.'.'.$respid;
 1603: 
 1604: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 1605:     }
 1606:     $result='<input type="hidden" name="partlist'.$counter.
 1607: 	'" value="'.(join ":",@partlist).'" />'."\n";
 1608:     $result.='<input type="hidden" name="gradePartRespid'.
 1609: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 1610:     my $ctr = 0;
 1611:     while ($ctr < scalar(@partlist)) {
 1612: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 1613: 	    $partlist[$ctr].'" />'."\n";
 1614: 	$ctr++;
 1615:     }
 1616:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
 1617: 
 1618:     # print end of form
 1619:     if ($counter == $total) {
 1620: 	my $endform='<table border="0"><tr><td>'."\n";
 1621: 	$endform.='<input type="button" value="Save & Next" '.
 1622: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 1623: 	    $total.','.scalar(@partlist).');" TARGET=_self> &nbsp;'."\n";
 1624: 	my $ntstu ='<select name="NTSTU">'.
 1625: 	    '<option>1</option><option>2</option>'.
 1626: 	    '<option>3</option><option>5</option>'.
 1627: 	    '<option>7</option><option>10</option></select>'."\n";
 1628: 	my $nsel = ($ENV{'form.NTSTU'} ne '' ? $ENV{'form.NTSTU'} : '1');
 1629: 	$ntstu =~ s/<option>$nsel</<option selected="on">$nsel</;
 1630: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
 1631: 	$endform.='<input type="button" value="Previous" '.
 1632: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" TARGET=_self> &nbsp;'."\n".
 1633: 	    '<input type="button" value="Next" '.
 1634: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" TARGET=_self> &nbsp;';
 1635: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
 1636: 	$endform.='</td><tr></table></form>';
 1637: 	$endform.=&show_grading_menu_form($symb,$url);
 1638: 	$request->print($endform);
 1639:     }
 1640:     return '';
 1641: }
 1642: 
 1643: #--- Retrieve the last submission for all the parts
 1644: sub get_last_submission {
 1645:     my ($returnhash)=@_;
 1646:     my (@string,$timestamp);
 1647:     if ($$returnhash{'version'}) {
 1648: 	my %lasthash=();
 1649: 	my ($version);
 1650: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 1651: 	    foreach (sort(split(/\:/,$$returnhash{$version.':keys'}))) {
 1652: 		$lasthash{$_}=$$returnhash{$version.':'.$_};
 1653: 		   $timestamp = scalar(localtime($$returnhash{$version.':timestamp'}));
 1654: 	    }
 1655: 	}
 1656: 	foreach ((keys %lasthash)) {
 1657: 	    if ($_ =~ /\.submission$/) {
 1658: 		my ($partid,$foo) = split(/submission$/,$_);
 1659: 		my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 1660: 		    '<font color="red">Draft Copy</font> ' : '';
 1661: 		push @string, (join(':',$_,$draft.$lasthash{$_}));
 1662: 	    }
 1663: 	}
 1664:     }
 1665:     @string = $string[0] eq '' ? '<font color="red">Nothing submitted - no attempts.</font>' : @string;
 1666:     return \@string,\$timestamp;
 1667: }
 1668: 
 1669: #--- High light keywords, with style choosen by user.
 1670: sub keywords_highlight {
 1671:     my $string    = shift;
 1672:     my $size      = $ENV{'form.kwsize'} eq '0' ? '' : 'size='.$ENV{'form.kwsize'};
 1673:     my $styleon   = $ENV{'form.kwstyle'} eq ''  ? '' : $ENV{'form.kwstyle'};
 1674:     (my $styleoff = $styleon) =~ s/\</\<\//;
 1675:     my @keylist   = split(/[,\s+]/,$ENV{'form.keywords'});
 1676:     foreach (@keylist) {
 1677: 	$string =~ s/\b\Q$_\E(\b|\.)/<font color\=$ENV{'form.kwclr'} $size\>$styleon$_$styleoff<\/font>/gi;
 1678:     }
 1679:     return $string;
 1680: }
 1681: 
 1682: #--- Called from submission routine
 1683: sub processHandGrade {
 1684:     my ($request) = shift;
 1685:     my $url    = $ENV{'form.url'};
 1686:     my $symb   = $ENV{'form.symb'};
 1687:     my $button = $ENV{'form.gradeOpt'};
 1688:     my $ngrade = $ENV{'form.NCT'};
 1689:     my $ntstu  = $ENV{'form.NTSTU'};
 1690:     if ($button eq 'Save & Next') {
 1691: 	my $ctr = 0;
 1692: 	while ($ctr < $ngrade) {
 1693: 	    my ($uname,$udom) = split(/:/,$ENV{'form.unamedom'.$ctr});
 1694: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$url,$symb,$uname,$udom,$ctr);
 1695: 	    if ($errorflag eq 'no_score') {
 1696: 		$ctr++;
 1697: 		next;
 1698: 	    }
 1699: 	    if ($errorflag eq 'not_allowed') {
 1700: 		$request->print("<font color=\"red\">Not allowed to modify grades for $uname:$udom</font>");
 1701: 		$ctr++;
 1702: 		next;
 1703: 	    }
 1704: 	    my $includemsg = $ENV{'form.includemsg'.$ctr};
 1705: 	    my ($subject,$message,$msgstatus) = ('','','');
 1706: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 1707: 		$subject = $ENV{'form.msgsub'} if ($includemsg =~ /^msgsub/);
 1708: 		my (@msgnum) = split(/,/,$includemsg);
 1709: 		foreach (@msgnum) {
 1710: 		    $message.=$ENV{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 1711: 		}
 1712: 		$message =&Apache::lonfeedback::clear_out_html($message);
 1713: 		$message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 1714: 		$message.=" for <a href=\"".
 1715: 		    &Apache::lonnet::clutter($url).
 1716: 		    "?symb=$symb\">$ENV{'form.probTitle'}</a>";
 1717: 		$msgstatus = &Apache::lonmsg::user_normal_msg ($uname,$udom,
 1718: 							       $ENV{'form.msgsub'},$message);
 1719: 	    }
 1720: 	    if ($ENV{'form.collaborator'.$ctr}) {
 1721: 		my (@collaborators) = split(/:/,$ENV{'form.collaborator'.$ctr});
 1722: 		foreach (@collaborators) {
 1723: 		    my ($errorflag,$pts,$wgt) = 
 1724: 			&saveHandGrade($request,$url,$symb,$_,$udom,$ctr,$ENV{'form.unamedom'.$ctr});
 1725: 		    if ($errorflag eq 'not_allowed') {
 1726: 			$request->print("<font color=\"red\">Not allowed to modify grades for $_:$udom</font>");
 1727: 			next;
 1728: 		    } else {
 1729: 			if ($message ne '') {
 1730: 			    $msgstatus = &Apache::lonmsg::user_normal_msg ($_,$udom,
 1731: 									   $ENV{'form.msgsub'},
 1732: 									   $message);
 1733: 			}
 1734: 		    }
 1735: 		}
 1736: 	    }
 1737: 	    $ctr++;
 1738: 	}
 1739:     }
 1740: 
 1741:     if ($ENV{'form.handgrade'} eq 'yes') {
 1742: 	# Keywords sorted in alphabatical order
 1743: 	my $loginuser = $ENV{'user.name'}.':'.$ENV{'user.domain'};
 1744: 	my %keyhash = ();
 1745: 	$ENV{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 1746: 	$ENV{'form.keywords'}           =~ s/^\s+|\s+$//;
 1747: 	my (@keywords) = sort(split(/\s+/,$ENV{'form.keywords'}));
 1748: 	$ENV{'form.keywords'} = join(' ',@keywords);
 1749: 	$keyhash{$symb.'_keywords'}     = $ENV{'form.keywords'};
 1750: 	$keyhash{$symb.'_subject'}      = $ENV{'form.msgsub'};
 1751: 	$keyhash{$loginuser.'_kwclr'}   = $ENV{'form.kwclr'};
 1752: 	$keyhash{$loginuser.'_kwsize'}  = $ENV{'form.kwsize'};
 1753: 	$keyhash{$loginuser.'_kwstyle'} = $ENV{'form.kwstyle'};
 1754: 
 1755: 	# message center - Order of message gets changed. Blank line is eliminated.
 1756: 	# New messages are saved in ENV for the next student.
 1757: 	# All messages are saved in nohist_handgrade.db
 1758: 	my ($ctr,$idx) = (1,1);
 1759: 	while ($ctr <= $ENV{'form.savemsgN'}) {
 1760: 	    if ($ENV{'form.savemsg'.$ctr} ne '') {
 1761: 		$keyhash{$symb.'_savemsg'.$idx} = $ENV{'form.savemsg'.$ctr};
 1762: 		$idx++;
 1763: 	    }
 1764: 	    $ctr++;
 1765: 	}
 1766: 	$ctr = 0;
 1767: 	while ($ctr < $ngrade) {
 1768: 	    if ($ENV{'form.newmsg'.$ctr} ne '') {
 1769: 		$keyhash{$symb.'_savemsg'.$idx} = $ENV{'form.newmsg'.$ctr};
 1770: 		$ENV{'form.savemsg'.$idx} = $ENV{'form.newmsg'.$ctr};
 1771: 		$idx++;
 1772: 	    }
 1773: 	    $ctr++;
 1774: 	}
 1775: 	$ENV{'form.savemsgN'} = --$idx;
 1776: 	$keyhash{$symb.'_savemsgN'} = $ENV{'form.savemsgN'};
 1777: 	my $putresult = &Apache::lonnet::put
 1778: 	    ('nohist_handgrade',\%keyhash,
 1779: 	     $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
 1780: 	     $ENV{'course.'.$ENV{'request.course.id'}.'.num'});
 1781:     }
 1782:     # Called by Save & Refresh from Highlight Attribute Window
 1783:     my (undef,undef,$fullname) = &getclasslist($ENV{'form.section'},'1');
 1784:     if ($ENV{'form.refresh'} eq 'on') {
 1785: 	my ($ctr,$total) = (0,0);
 1786: 	while ($ctr < $ngrade) {
 1787: 	    $total++ if  $ENV{'form.unamedom'.$ctr} ne '';
 1788: 	    $ctr++;
 1789: 	}
 1790: 	$ENV{'form.NTSTU'}=$ngrade;
 1791: 	$ctr = 0;
 1792: 	while ($ctr < $total) {
 1793: 	    my $processUser = $ENV{'form.unamedom'.$ctr};
 1794: 	    ($ENV{'form.student'},$ENV{'form.userdom'}) = split(/:/,$processUser);
 1795: 	    $ENV{'form.fullname'} = $$fullname{$processUser};
 1796: 	    &submission($request,$ctr,$total-1);
 1797: 	    $ctr++;
 1798: 	}
 1799: 	return '';
 1800:     }
 1801: 
 1802: # Go directly to grade student - from submission or link from chart page
 1803:     if ($button eq 'Grade Student') {
 1804: 	(undef,undef,$ENV{'form.handgrade'},undef,undef) = &showResourceInfo($url);
 1805: 	my $processUser = $ENV{'form.unamedom'.$ENV{'form.studentNo'}};
 1806: 	($ENV{'form.student'},$ENV{'form.userdom'}) = split(/:/,$processUser);
 1807: 	$ENV{'form.fullname'} = $$fullname{$processUser};
 1808: 	&submission($request,0,0);
 1809: 	return '';
 1810:     }
 1811: 
 1812:     # Get the next/previous one or group of students
 1813:     my $firststu = $ENV{'form.unamedom0'};
 1814:     my $laststu = $ENV{'form.unamedom'.($ngrade-1)};
 1815:     my $ctr = 2;
 1816:     while ($laststu eq '') {
 1817: 	$laststu  = $ENV{'form.unamedom'.($ngrade-$ctr)};
 1818: 	$ctr++;
 1819: 	$laststu = $firststu if ($ctr > $ngrade);
 1820:     }
 1821: 
 1822:     my (@parsedlist,@nextlist);
 1823:     my ($nextflg) = 0;
 1824:     foreach (sort {lc($$fullname{$a}) cmp lc($$fullname{$b}) } keys %$fullname) {
 1825: 	if ($nextflg == 1 && $button =~ /Next$/) {
 1826: 	    push @parsedlist,$_;
 1827: 	}
 1828: 	$nextflg = 1 if ($_ eq $laststu);
 1829: 	if ($button eq 'Previous') {
 1830: 	    last if ($_ eq $firststu);
 1831: 	    push @parsedlist,$_;
 1832: 	}
 1833:     }
 1834:     $ctr = 0;
 1835:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 1836:     my ($partlist) = &response_type($url);
 1837:     foreach my $student (@parsedlist) {
 1838: 	my $submitonly=$ENV{'form.submitonly'};
 1839: 	my ($uname,$udom) = split(/:/,$student);
 1840: 	if ($submitonly =~ /^(yes|graded)$/) {
 1841: #	    my %record = &Apache::lonnet::restore($symb,$ENV{'request.course.id'},$udom,$uname);
 1842: 	    my %status=&student_gradeStatus($url,$symb,$udom,$uname,$partlist);
 1843: 	    my $submitted = 0;
 1844: 	    my $graded = 1;
 1845: 	    foreach (keys(%status)) {
 1846: 		$submitted = 1 if ($status{$_} ne 'nothing');
 1847: 		$graded = 0 if ($status{$_} =~ /^correct/);
 1848: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 1849: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 1850: 		    $submitted = 0;
 1851: 		}
 1852: 	    }
 1853: 	    next if (!$submitted && ($submitonly eq 'yes' || $submitonly eq 'graded'));
 1854: 	    next if (!$graded && $submitonly eq 'graded');
 1855: 	}
 1856: 	push @nextlist,$student if ($ctr < $ntstu);
 1857: 	last if ($ctr == $ntstu);
 1858: 	$ctr++;
 1859:     }
 1860: 
 1861:     $ctr = 0;
 1862:     my $total = scalar(@nextlist)-1;
 1863: 
 1864:     foreach (sort @nextlist) {
 1865: 	my ($uname,$udom,$submitter) = split(/:/);
 1866: 	$ENV{'form.student'}  = $uname;
 1867: 	$ENV{'form.userdom'}  = $udom;
 1868: 	$ENV{'form.fullname'} = $$fullname{$_};
 1869: 	&submission($request,$ctr,$total);
 1870: 	$ctr++;
 1871:     }
 1872:     if ($total < 0) {
 1873: 	my $the_end = '<h3><font color="red">LON-CAPA User Message</font></h3><br />'."\n";
 1874: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
 1875: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
 1876: 	$the_end.=&show_grading_menu_form ($symb,$url);
 1877: 	$request->print($the_end);
 1878:     }
 1879:     return '';
 1880: }
 1881: 
 1882: #---- Save the score and award for each student, if changed
 1883: sub saveHandGrade {
 1884:     my ($request,$url,$symb,$stuname,$domain,$newflg,$submitter) = @_;
 1885:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 1886: 					   $ENV{'request.course.id'});
 1887:     if (!&canmodify($usec)) { return('not_allowed'); }
 1888:     my %record     = &Apache::lonnet::restore($symb,$ENV{'request.course.id'},$domain,$stuname);
 1889:     my %newrecord  = ();
 1890:     my ($pts,$wgt) = ('','');
 1891:     foreach (split(/:/,$ENV{'form.partlist'.$newflg})) {
 1892: 	my $dropMenu = $ENV{'form.GD_SEL'.$newflg.'_'.$_};
 1893: 	if ($dropMenu eq 'excused') {
 1894: 	    if ($record{'resource.'.$_.'.solved'} ne 'excused') {
 1895: 		$newrecord{'resource.'.$_.'.solved'} = 'excused';
 1896: 		if (exists($record{'resource.'.$_.'.awarded'})) {
 1897: 		    $newrecord{'resource.'.$_.'.awarded'} = '';
 1898: 		}
 1899: 	    $newrecord{'resource.'.$_.'.regrader'}="$ENV{'user.name'}:$ENV{'user.domain'}";
 1900: 	    }
 1901: 	} elsif ($dropMenu eq 'reset status'
 1902: 		 && exists($record{'resource.'.$_.'.solved'})) { #don't bother if no old records -> no attempts
 1903: 	    $newrecord{'resource.'.$_.'.tries'} = 0;
 1904: 	    $newrecord{'resource.'.$_.'.solved'} = '';
 1905: 	    $newrecord{'resource.'.$_.'.award'} = '';
 1906: 	    $newrecord{'resource.'.$_.'.awarded'} = 0;
 1907: 	    $newrecord{'resource.'.$_.'.regrader'}="$ENV{'user.name'}:$ENV{'user.domain'}";
 1908: 	} elsif ($dropMenu eq '') {
 1909: 	    $pts = ($ENV{'form.GD_BOX'.$newflg.'_'.$_} ne '' ? 
 1910: 		    $ENV{'form.GD_BOX'.$newflg.'_'.$_} : 
 1911: 		    $ENV{'form.RADVAL'.$newflg.'_'.$_});
 1912: 	    return 'no_score' if ($pts eq '' && $ENV{'form.GD_SEL'.$newflg.'_'.$_} eq '');
 1913: 	    $wgt = $ENV{'form.WGT'.$newflg.'_'.$_} eq '' ? 1 : 
 1914: 		$ENV{'form.WGT'.$newflg.'_'.$_};
 1915: 	    my $partial= $pts/$wgt;
 1916: 	    next if ($partial eq $record{'resource.'.$_.'.awarded'}); #do not update score for part if not changed.
 1917: 	    $newrecord{'resource.'.$_.'.awarded'}  = $partial 
 1918: 		if ($record{'resource.'.$_.'.awarded'} ne $partial);
 1919: 	    my $reckey = 'resource.'.$_.'.solved';
 1920: 	    if ($partial == 0) {
 1921: 		$newrecord{$reckey} = 'incorrect_by_override' 
 1922: 		    if ($record{$reckey} ne 'incorrect_by_override');
 1923: 	    } else {
 1924: 		$newrecord{$reckey} = 'correct_by_override' 
 1925: 		    if ($record{$reckey} ne 'correct_by_override');
 1926: 	    }
 1927: 	    $newrecord{'resource.'.$_.'.submitted_by'} = $submitter 
 1928: 		if ($submitter && ($record{'resource.'.$_.'.submitted_by'} ne $submitter));
 1929: 	    $newrecord{'resource.'.$_.'.regrader'}="$ENV{'user.name'}:$ENV{'user.domain'}";
 1930: 	}
 1931:     }
 1932: 
 1933:     if (scalar(keys(%newrecord)) > 0) {
 1934: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 1935: 				$ENV{'request.course.id'},$domain,$stuname);
 1936:     }
 1937:     return '',$pts,$wgt;
 1938: }
 1939: 
 1940: #--------------------------------------------------------------------------------------
 1941: #
 1942: #-------------------------- Next few routines handles grading by section or whole class
 1943: #
 1944: #--- Javascript to handle grading by section or whole class
 1945: sub viewgrades_js {
 1946:     my ($request) = shift;
 1947: 
 1948:     $request->print(<<VIEWJAVASCRIPT);
 1949: <script type="text/javascript" language="javascript">
 1950:    function writePoint(partid,weight,point) {
 1951: 	var radioButton = document.classgrade["RADVAL_"+partid];
 1952: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 1953: 	if (point == "textval") {
 1954: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 1955: 	    if (isNaN(point) || parseFloat(point) < 0) {
 1956: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 1957: 		var resetbox = false;
 1958: 		for (var i=0; i<radioButton.length; i++) {
 1959: 		    if (radioButton[i].checked) {
 1960: 			textbox.value = i;
 1961: 			resetbox = true;
 1962: 		    }
 1963: 		}
 1964: 		if (!resetbox) {
 1965: 		    textbox.value = "";
 1966: 		}
 1967: 		return;
 1968: 	    }
 1969: 	    if (parseFloat(point) > parseFloat(weight)) {
 1970: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 1971: 				   ") greater than the weight for the part. Accept?");
 1972: 		if (resp == false) {
 1973: 		    textbox.value = "";
 1974: 		    return;
 1975: 		}
 1976: 	    }
 1977: 	    for (var i=0; i<radioButton.length; i++) {
 1978: 		radioButton[i].checked=false;
 1979: 		if (parseFloat(point) == i) {
 1980: 		    radioButton[i].checked=true;
 1981: 		}
 1982: 	    }
 1983: 
 1984: 	} else {
 1985: 	    textbox.value = parseFloat(point);
 1986: 	}
 1987: 	for (i=0;i<document.classgrade.total.value;i++) {
 1988: 	    var user = document.classgrade["ctr"+i].value;
 1989: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 1990: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 1991: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 1992: 	    if (saveval != "correct") {
 1993: 		scorename.value = point;
 1994: 		if (selname[0].selected != true) {
 1995: 		    selname[0].selected = true;
 1996: 		}
 1997: 	    }
 1998: 	}
 1999: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 2000:     }
 2001: 
 2002:     function writeRadText(partid,weight) {
 2003: 	var selval   = document.classgrade["SELVAL_"+partid];
 2004: 	var radioButton = document.classgrade["RADVAL_"+partid];
 2005: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 2006: 	if (selval[1].selected || selval[2].selected) {
 2007: 	    for (var i=0; i<radioButton.length; i++) {
 2008: 		radioButton[i].checked=false;
 2009: 
 2010: 	    }
 2011: 	    textbox.value = "";
 2012: 
 2013: 	    for (i=0;i<document.classgrade.total.value;i++) {
 2014: 		var user = document.classgrade["ctr"+i].value;
 2015: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 2016: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 2017: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 2018: 		if (saveval != "correct") {
 2019: 		    scorename.value = "";
 2020: 		    if (selval[1].selected) {
 2021: 			selname[1].selected = true;
 2022: 		    } else {
 2023: 			selname[2].selected = true;
 2024: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 2025: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 2026: 		    }
 2027: 		}
 2028: 	    }
 2029: 	} else {
 2030: 	    for (i=0;i<document.classgrade.total.value;i++) {
 2031: 		var user = document.classgrade["ctr"+i].value;
 2032: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 2033: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 2034: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 2035: 		if (saveval != "correct") {
 2036: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 2037: 		    selname[0].selected = true;
 2038: 		}
 2039: 	    }
 2040: 	}	    
 2041:     }
 2042: 
 2043:     function changeSelect(partid,user) {
 2044: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 2045: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 2046: 	var point  = textbox.value;
 2047: 	var weight = document.classgrade["weight_"+partid].value;
 2048: 
 2049: 	if (isNaN(point) || parseFloat(point) < 0) {
 2050: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 2051: 	    textbox.value = "";
 2052: 	    return;
 2053: 	}
 2054: 	if (parseFloat(point) > parseFloat(weight)) {
 2055: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 2056: 			       ") greater than the weight of the part. Accept?");
 2057: 	    if (resp == false) {
 2058: 		textbox.value = "";
 2059: 		return;
 2060: 	    }
 2061: 	}
 2062: 	selval[0].selected = true;
 2063:     }
 2064: 
 2065:     function changeOneScore(partid,user) {
 2066: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 2067: 	if (selval[1].selected || selval[2].selected) {
 2068: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 2069: 	    if (selval[2].selected) {
 2070: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 2071: 	    }
 2072: 	}
 2073:     }
 2074: 
 2075:     function resetEntry(numpart) {
 2076: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 2077: 	    var partid = document.classgrade["partid_"+ctpart].value;
 2078: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 2079: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 2080: 	    var selval  = document.classgrade["SELVAL_"+partid];
 2081: 	    for (var i=0; i<radioButton.length; i++) {
 2082: 		radioButton[i].checked=false;
 2083: 
 2084: 	    }
 2085: 	    textbox.value = "";
 2086: 	    selval[0].selected = true;
 2087: 
 2088: 	    for (i=0;i<document.classgrade.total.value;i++) {
 2089: 		var user = document.classgrade["ctr"+i].value;
 2090: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 2091: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 2092: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 2093: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 2094: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 2095: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 2096: 		if (saveselval == "excused") {
 2097: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 2098: 		} else {
 2099: 		    if (selname[0].selected == false) {selname[0].selected = true};
 2100: 		}
 2101: 	    }
 2102: 	}
 2103:     }
 2104: 
 2105: </script>
 2106: VIEWJAVASCRIPT
 2107: }
 2108: 
 2109: #--- show scores for a section or whole class w/ option to change/update a score
 2110: sub viewgrades {
 2111:     my ($request) = shift;
 2112:     &viewgrades_js($request);
 2113: 
 2114:     my ($symb,$url) = ($ENV{'form.symb'},$ENV{'form.url'}); 
 2115:     my $result='<h3><font color="#339933">Manual Grading</font></h3>';
 2116: 
 2117:     $result.='<font size=+1><b>Current Resource: </b>'.$ENV{'form.probTitle'}.'</font>'."\n";
 2118: 
 2119:     #view individual student submission form - called using Javascript viewOneStudent
 2120:     $result.=&jscriptNform($url,$symb);
 2121: 
 2122:     #beginning of class grading form
 2123:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 2124: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
 2125: 	'<input type="hidden" name="url"     value="'.$url.'" />'."\n".
 2126: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 2127: 	'<input type="hidden" name="section" value="'.$ENV{'form.section'}.'" />'."\n".
 2128: 	'<input type="hidden" name="saveState" value="'.$ENV{'form.saveState'}.'" />'."\n".
 2129: 	'<input type="hidden" name="Status" value="'.$ENV{'form.Status'}.'" />'."\n".
 2130: 	'<input type="hidden" name="probTitle" value="'.$ENV{'form.probTitle'}.'" />'."\n";
 2131: 
 2132:     my $sectionClass;
 2133:     if ($ENV{'form.section'} eq 'all') {
 2134: 	$sectionClass='Class </h3>';
 2135:     } elsif ($ENV{'form.section'} eq 'no') {
 2136: 	$sectionClass='Students in no Section </h3>';
 2137:     } else {
 2138: 	$sectionClass='Students in Section '.$ENV{'form.section'}.'</h3>';
 2139:     }
 2140:     $result.='<h3>Assign Common Grade To '.$sectionClass;
 2141:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
 2142: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
 2143:     #radio buttons/text box for assigning points for a section or class.
 2144:     #handles different parts of a problem
 2145:     my ($partlist,$handgrade) = &response_type($url,$symb);
 2146:     my %weight = ();
 2147:     my $ctsparts = 0;
 2148:     $result.='<table border="0">';
 2149:     my %seen = ();
 2150:     for (sort keys(%$handgrade)) {
 2151: 	my ($partid,$respid) = split (/_/,$_,2);
 2152: 	next if $seen{$partid};
 2153: 	$seen{$partid}++;
 2154: 	my ($responsetype,$handgrade)=split(/:/,$$handgrade{$_});
 2155: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 2156: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 2157: 
 2158: 	$result.='<input type="hidden" name="partid_'.
 2159: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 2160: 	$result.='<input type="hidden" name="weight_'.
 2161: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 2162: 	$result.='<tr><td><b>Part  '.$partid.'&nbsp; &nbsp;Point:</b> </td><td>';
 2163: 	$result.='<table border="0"><tr>';  
 2164: 	my $ctr = 0;
 2165: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 2166: 	    $result.= '<td><input type="radio" name="RADVAL_'.$partid.'" '.
 2167: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 2168: 		','.$ctr.')" />'.$ctr."</td>\n";
 2169: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 2170: 	    $ctr++;
 2171: 	}
 2172: 	$result.='</tr></table>';
 2173: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
 2174: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 2175: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 2176: 	    $weight{$partid}.' (problem weight)</td>'."\n";
 2177: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
 2178: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 2179: 		$weight{$partid}.')"> '.
 2180: 	    '<option selected="on"> </option>'.
 2181: 	    '<option>excused</option>'.
 2182: 	    '<option>reset status</option></select></td></tr>'."\n";
 2183: 	$ctsparts++;
 2184:     }
 2185:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
 2186: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 2187:     $result.='<input type="button" value="Reset" '.
 2188: 	'onClick="javascript:resetEntry('.$ctsparts.');" TARGET=_self>';
 2189: 
 2190:     #table listing all the students in a section/class
 2191:     #header of table
 2192:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
 2193:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
 2194: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
 2195: 	'<td>'.&nameUserString('header')."</td>\n";
 2196:     my (@parts) = sort(&getpartlist($url));
 2197:     foreach my $part (@parts) {
 2198: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 2199: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
 2200: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 2201: 	if ($display =~ /^Partial Credit Factor/) {
 2202: 	    my ($partid) = &split_part_type($part);
 2203: 	    $result.='<td><b>Score Part '.$partid.'<br />(weight = '.
 2204: 		$weight{$partid}.')</b></td>'."\n";
 2205: 	    next;
 2206: 	}
 2207: 	$display =~ s|Problem Status|Grade Status<br />|;
 2208: 	$result.='<td><b>'.$display.'</b></td>'."\n";
 2209:     }
 2210:     $result.='</tr>';
 2211: 
 2212:     #get info for each student
 2213:     #list all the students - with points and grade status
 2214:     my (undef,undef,$fullname) = &getclasslist($ENV{'form.section'},'1');
 2215:     my $ctr = 0;
 2216:     foreach (sort {lc($$fullname{$a}) cmp lc($$fullname{$b}) } keys %$fullname) {
 2217: 	my $uname = $_;
 2218: 	$uname=~s/:/_/;
 2219: 	$result.='<input type="hidden" name="ctr'.$ctr.'" value="'.$uname.'" />'."\n";
 2220: 	$ctr++;
 2221: 	$result.=&viewstudentgrade($url,$symb,$ENV{'request.course.id'},
 2222: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr);
 2223:     }
 2224:     $result.='</table></td></tr></table>';
 2225:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 2226:     $result.='<input type="button" value="Save" '.
 2227: 	'onClick="javascript:submit();" TARGET=_self /></form>'."\n";
 2228:     if (scalar(%$fullname) eq 0) {
 2229: 	my $colspan=3+scalar(@parts);
 2230: 	$result='<font color="red">There are no students in section "'.$ENV{'form.section'}.
 2231: 	    '" with enrollment status "'.$ENV{'form.Status'}.'" to modify or grade.</font>';
 2232:     }
 2233:     $result.=&show_grading_menu_form($symb,$url);
 2234:     return $result;
 2235: }
 2236: 
 2237: #--- call by previous routine to display each student
 2238: sub viewstudentgrade {
 2239:     my ($url,$symb,$courseid,$student,$fullname,$parts,$weight,$ctr) = @_;
 2240:     my ($uname,$udom) = split(/:/,$student);
 2241:     $student=~s/:/_/;
 2242:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 2243:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.$ctr.'&nbsp;</td><td>&nbsp;'.
 2244: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 2245: 	'\')"; TARGET=_self>'.$fullname.'</a> '.
 2246: 	'<font color="#999999">('.$uname.($ENV{'user.domain'} eq $udom ? '' : ':'.$udom).')</font></td>'."\n";
 2247:     foreach my $apart (@$parts) {
 2248: 	my ($part,$type) = &split_part_type($apart);
 2249: 	my $score=$record{"resource.$part.$type"};
 2250: 	if ($type eq 'awarded') {
 2251: 	    my $pts = $score eq '' ? '' : $score*$$weight{$part};
 2252: 	    $result.='<input type="hidden" name="'.
 2253: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 2254: 	    $result.='<td align="middle"><input type="text" name="'.
 2255: 		'GD_'.$student.'_'.$part.'_awarded" '.
 2256: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 2257: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 2258: 	} elsif ($type eq 'solved') {
 2259: 	    my ($status,$foo)=split(/_/,$score,2);
 2260: 	    $status = 'nothing' if ($status eq '');
 2261: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 2262: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 2263: 	    $result.='<td align="middle">&nbsp;<select name="'.
 2264: 		'GD_'.$student.'_'.$part.'_solved" '.
 2265: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 2266: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="on">excused</option>' 
 2267: 		: '<option selected="on"> </option><option>excused</option>')."\n";
 2268: 	    $result.='<option>reset status</option>';
 2269: 	    $result.="</select>&nbsp;</td>\n";
 2270: 	} else {
 2271: 	    $result.='<input type="hidden" name="'.
 2272: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 2273: 		    "\n";
 2274: 	    $result.='<td align="middle"><input type="text" name="'.
 2275: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 2276: 		'value="'.$score.'" size="4" /></td>'."\n";
 2277: 	}
 2278:     }
 2279:     $result.='</tr>';
 2280:     return $result;
 2281: }
 2282: 
 2283: #--- change scores for all the students in a section/class
 2284: #    record does not get update if unchanged
 2285: sub editgrades {
 2286:     my ($request) = @_;
 2287: 
 2288:     my $symb=$ENV{'form.symb'};
 2289:     my $url =$ENV{'form.url'};
 2290:     my $title='<h3><font color="#339933">Current Grade Status</font></h3>';
 2291:     $title.='<font size=+1><b>Current Resource: </b>'.$ENV{'form.probTitle'}.'</font><br />'."\n";
 2292:     $title.='<font size=+1><b>Section: </b>'.$ENV{'form.section'}.'</font>'."\n";
 2293: 
 2294:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
 2295:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
 2296: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
 2297: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
 2298: 
 2299:     my %scoreptr = (
 2300: 		    'correct'  =>'correct_by_override',
 2301: 		    'incorrect'=>'incorrect_by_override',
 2302: 		    'excused'  =>'excused',
 2303: 		    'ungraded' =>'ungraded_attempted',
 2304: 		    'nothing'  => '',
 2305: 		    );
 2306:     my ($classlist,undef,$fullname) = &getclasslist($ENV{'form.section'},'0');
 2307: 
 2308:     my (@partid);
 2309:     my %weight = ();
 2310:     my %columns = ();
 2311:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 2312: 
 2313:     my (@parts) = sort(&getpartlist($url));
 2314:     my $header;
 2315:     while ($ctr < $ENV{'form.totalparts'}) {
 2316: 	my $partid = $ENV{'form.partid_'.$ctr};
 2317: 	push @partid,$partid;
 2318: 	$weight{$partid} = $ENV{'form.weight_'.$partid};
 2319: 	$ctr++;
 2320:     }
 2321:     foreach my $partid (@partid) {
 2322: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
 2323: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
 2324: 	$columns{$partid}=2;
 2325: 	foreach my $stores (@parts) {
 2326: 	    my ($part,$type) = &split_part_type($stores);
 2327: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 2328: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 2329: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 2330: 	    $display =~ s/\[Part: (\w)+\]//;
 2331: 	    $display =~ s/Number of Attempts/Tries/;
 2332: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
 2333: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
 2334: 	    $columns{$partid}+=2;
 2335: 	}
 2336:     }
 2337:     foreach my $partid (@partid) {
 2338: 	$result .= '<td colspan="'.$columns{$partid}.
 2339: 	    '" align="center"><b>Part '.$partid.
 2340: 	    '</b> (Weight = '.$weight{$partid}.')</td>';
 2341: 
 2342:     }
 2343:     $result .= '</tr><tr bgcolor="#deffff">';
 2344:     $result .= $header;
 2345:     $result .= '</tr>'."\n";
 2346:     my $noupdate;
 2347:     my ($updateCtr,$noupdateCtr) = (1,1);
 2348:     for ($i=0; $i<$ENV{'form.total'}; $i++) {
 2349: 	my $line;
 2350: 	my $user = $ENV{'form.ctr'.$i};
 2351: 	my $usercolon = $user;
 2352: 	$usercolon =~s/_/:/;
 2353: 	my ($uname,$udom)=split(/_/,$user);
 2354: 	my %newrecord;
 2355: 	my $updateflag = 0;
 2356: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$usercolon},$uname,$udom).'</td>';
 2357: 	my $usec=$classlist->{"$uname:$udom"}[5];
 2358: 	if (!&canmodify($usec)) {
 2359: 	    my $numcols=scalar(@partid)*4+2;
 2360: 	    $noupdate.=$line."<td colspan=\"$numcols\"><font color=\"red\">Not allowed to modify student</font></td></tr>";
 2361: 	    next;
 2362: 	}
 2363: 	foreach (@partid) {
 2364: 	    my $old_aw    = $ENV{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 2365: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 2366: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 2367: 	    my $old_score = $scoreptr{$ENV{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 2368: 
 2369: 	    my $awarded   = $ENV{'form.GD_'.$user.'_'.$_.'_awarded'};
 2370: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 2371: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 2372: 	    my $score;
 2373: 	    if ($partial eq '') {
 2374: 		$score = $scoreptr{$ENV{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 2375: 	    } elsif ($partial > 0) {
 2376: 		$score = 'correct_by_override';
 2377: 	    } elsif ($partial == 0) {
 2378: 		$score = 'incorrect_by_override';
 2379: 	    }
 2380: 	    my $dropMenu = $ENV{'form.GD_'.$user.'_'.$_.'_solved'};
 2381: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 2382: 
 2383: 	    if ($dropMenu eq 'reset status' &&
 2384: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 2385: 		$newrecord{'resource.'.$_.'.tries'} = 0;
 2386: 		$newrecord{'resource.'.$_.'.solved'} = '';
 2387: 		$newrecord{'resource.'.$_.'.award'} = '';
 2388: 		$newrecord{'resource.'.$_.'.awarded'} = 0;
 2389: 		$newrecord{'resource.'.$_.'.regrader'}="$ENV{'user.name'}:$ENV{'user.domain'}";
 2390: 		$updateflag = 1;
 2391: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 2392: 		$updateflag = 1;
 2393: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 2394: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 2395: 		$rec_update++;
 2396: 	    }
 2397: 
 2398: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 2399: 		'<td align="center">'.$awarded.
 2400: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 2401: 
 2402: 
 2403: 	    my $partid=$_;
 2404: 	    foreach my $stores (@parts) {
 2405: 		my ($part,$type) = &split_part_type($stores);
 2406: 		if ($part !~ m/^\Q$partid\E/) { next;}
 2407: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 2408: 		my $old_aw    = $ENV{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 2409: 		my $awarded   = $ENV{'form.GD_'.$user.'_'.$part.'_'.$type};
 2410: 		if ($awarded ne '' && $awarded ne $old_aw) {
 2411: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 2412: 		    $newrecord{'resource.'.$part.'.regrader'}="$ENV{'user.name'}:$ENV{'user.domain'}";
 2413: 		    $updateflag=1;
 2414: 		}
 2415: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 2416: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 2417: 	    }
 2418: 	}
 2419: 	$line.='</tr>'."\n";
 2420: 	if ($updateflag) {
 2421: 	    $count++;
 2422: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$ENV{'request.course.id'},
 2423: 				    $udom,$uname);
 2424: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
 2425: 	    $updateCtr++;
 2426: 	} else {
 2427: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
 2428: 	    $noupdateCtr++;
 2429: 	}
 2430:     }
 2431:     if ($noupdate) {
 2432: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 2433: 	my $numcols=scalar(@partid)*4+2;
 2434: 	$result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr>'.$noupdate;
 2435:     }
 2436:     $result .= '</table></td></tr></table>'."\n".
 2437: 	&show_grading_menu_form ($symb,$url);
 2438:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
 2439: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
 2440: 	'<b>Total number of students = '.$ENV{'form.total'}.'</b><br />';
 2441:     return $title.$msg.$result;
 2442: }
 2443: 
 2444: sub split_part_type {
 2445:     my ($partstr) = @_;
 2446:     my ($temp,@allparts)=split(/_/,$partstr);
 2447:     my $type=pop(@allparts);
 2448:     my $part=join('.',@allparts);
 2449:     return ($part,$type);
 2450: }
 2451: 
 2452: #------------- end of section for handling grading by section/class ---------
 2453: #
 2454: #----------------------------------------------------------------------------
 2455: 
 2456: 
 2457: #----------------------------------------------------------------------------
 2458: #
 2459: #-------------------------- Next few routines handles grading by csv upload
 2460: #
 2461: #--- Javascript to handle csv upload
 2462: sub csvupload_javascript_reverse_associate {
 2463:   return(<<ENDPICK);
 2464:   function verify(vf) {
 2465:     var foundsomething=0;
 2466:     var founduname=0;
 2467:     var founddomain=0;
 2468:     for (i=0;i<=vf.nfields.value;i++) {
 2469:       tw=eval('vf.f'+i+'.selectedIndex');
 2470:       if (i==0 && tw!=0) { founduname=1; }
 2471:       if (i==1 && tw!=0) { founddomain=1; }
 2472:       if (i!=0 && i!=1 && tw!=0) { foundsomething=1; }
 2473:     }
 2474:     if (founduname==0 || founddomain==0) {
 2475:       alert('You need to specify at both the username and domain');
 2476:       return;
 2477:     }
 2478:     if (foundsomething==0) {
 2479:       alert('You need to specify at least one grading field');
 2480:       return;
 2481:     }
 2482:     vf.submit();
 2483:   }
 2484:   function flip(vf,tf) {
 2485:     var nw=eval('vf.f'+tf+'.selectedIndex');
 2486:     var i;
 2487:     for (i=0;i<=vf.nfields.value;i++) {
 2488:       //can not pick the same destination field for both name and domain
 2489:       if (((i ==0)||(i ==1)) && 
 2490:           ((tf==0)||(tf==1)) && 
 2491:           (i!=tf) &&
 2492:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 2493:         eval('vf.f'+i+'.selectedIndex=0;')
 2494:       }
 2495:     }
 2496:   }
 2497: ENDPICK
 2498: }
 2499: 
 2500: sub csvupload_javascript_forward_associate {
 2501:   return(<<ENDPICK);
 2502:   function verify(vf) {
 2503:     var foundsomething=0;
 2504:     var founduname=0;
 2505:     var founddomain=0;
 2506:     for (i=0;i<=vf.nfields.value;i++) {
 2507:       tw=eval('vf.f'+i+'.selectedIndex');
 2508:       if (tw==1) { founduname=1; }
 2509:       if (tw==2) { founddomain=1; }
 2510:       if (tw>2) { foundsomething=1; }
 2511:     }
 2512:     if (founduname==0 || founddomain==0) {
 2513:       alert('You need to specify at both the username and domain');
 2514:       return;
 2515:     }
 2516:     if (foundsomething==0) {
 2517:       alert('You need to specify at least one grading field');
 2518:       return;
 2519:     }
 2520:     vf.submit();
 2521:   }
 2522:   function flip(vf,tf) {
 2523:     var nw=eval('vf.f'+tf+'.selectedIndex');
 2524:     var i;
 2525:     //can not pick the same destination field twice
 2526:     for (i=0;i<=vf.nfields.value;i++) {
 2527:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 2528:         eval('vf.f'+i+'.selectedIndex=0;')
 2529:       }
 2530:     }
 2531:   }
 2532: ENDPICK
 2533: }
 2534: 
 2535: sub csvuploadmap_header {
 2536:     my ($request,$symb,$url,$datatoken,$distotal)= @_;
 2537:     my $javascript;
 2538:     if ($ENV{'form.upfile_associate'} eq 'reverse') {
 2539: 	$javascript=&csvupload_javascript_reverse_associate();
 2540:     } else {
 2541: 	$javascript=&csvupload_javascript_forward_associate();
 2542:     }
 2543: 
 2544:     my ($result) = &showResourceInfo($url,$ENV{'form.probTitle'});
 2545: 
 2546:     $request->print(<<ENDPICK);
 2547: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 2548: <h3><font color="#339933">Uploading Class Grades</font></h3>
 2549: $result
 2550: <hr>
 2551: <h3>Identify fields</h3>
 2552: Total number of records found in file: $distotal <hr />
 2553: Enter as many fields as you can. The system will inform you and bring you back
 2554: to this page if the data selected is insufficient to run your class.<hr />
 2555: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 2556: <input type="hidden" name="associate"  value="" />
 2557: <input type="hidden" name="phase"      value="three" />
 2558: <input type="hidden" name="datatoken"  value="$datatoken" />
 2559: <input type="hidden" name="fileupload" value="$ENV{'form.fileupload'}" />
 2560: <input type="hidden" name="upfiletype" value="$ENV{'form.upfiletype'}" />
 2561: <input type="hidden" name="upfile_associate" 
 2562:                                        value="$ENV{'form.upfile_associate'}" />
 2563: <input type="hidden" name="symb"       value="$symb" />
 2564: <input type="hidden" name="url"        value="$url" />
 2565: <input type="hidden" name="saveState"  value="$ENV{'form.saveState'}" />
 2566: <input type="hidden" name="probTitle"  value="$ENV{'form.probTitle'}" />
 2567: <input type="hidden" name="command"    value="csvuploadassign" />
 2568: <hr />
 2569: <script type="text/javascript" language="Javascript">
 2570: $javascript
 2571: </script>
 2572: ENDPICK
 2573:     return '';
 2574: 
 2575: }
 2576: 
 2577: sub csvupload_fields {
 2578:     my ($url) = @_;
 2579:     my (@parts) = &getpartlist($url);
 2580:     my @fields=(['username','Student Username'],['domain','Student Domain']);
 2581:     foreach my $part (sort(@parts)) {
 2582: 	my @datum;
 2583: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 2584: 	my $name=$part;
 2585: 	if  (!$display) { $display = $name; }
 2586: 	@datum=($name,$display);
 2587: 	push(@fields,\@datum);
 2588:     }
 2589:     return (@fields);
 2590: }
 2591: 
 2592: sub csvuploadmap_footer {
 2593:     my ($request,$i,$keyfields) =@_;
 2594:     $request->print(<<ENDPICK);
 2595: </table>
 2596: <input type="hidden" name="nfields" value="$i" />
 2597: <input type="hidden" name="keyfields" value="$keyfields" />
 2598: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 2599: </form>
 2600: ENDPICK
 2601: }
 2602: 
 2603: sub upcsvScores_form {
 2604:     my ($request) = shift;
 2605:     my ($symb,$url)=&get_symb_and_url($request);
 2606:     if (!$symb) {return '';}
 2607:     my $result =<<CSVFORMJS;
 2608: <script type="text/javascript" language="javascript">
 2609:     function checkUpload(formname) {
 2610: 	if (formname.upfile.value == "") {
 2611: 	    alert("Please use the browse button to select a file from your local directory.");
 2612: 	    return false;
 2613: 	}
 2614: 	formname.submit();
 2615:     }
 2616:     </script>
 2617: CSVFORMJS
 2618:     $ENV{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 2619:     my ($table) = &showResourceInfo($url,$ENV{'form.probTitle'});
 2620:     $result.=$table;
 2621:     $result.='<br /><table width=100% border=0><tr><td bgcolor="#777777">'."\n";
 2622:     $result.='<table width=100% border=0><tr bgcolor="#e6ffff"><td>'."\n";
 2623:     $result.='&nbsp;<b>Specify a file containing the class scores for current resource'.
 2624: 	'.</b></td></tr>'."\n";
 2625:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 2626:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 2627:     $result.=<<ENDUPFORM;
 2628: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 2629: <input type="hidden" name="symb" value="$symb" />
 2630: <input type="hidden" name="url" value="$url" />
 2631: <input type="hidden" name="command" value="csvuploadmap" />
 2632: <input type="hidden" name="probTitle" value="$ENV{'form.probTitle'}" />
 2633: <input type="hidden" name="saveState"  value="$ENV{'form.saveState'}" />
 2634: $upfile_select
 2635: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scores" />
 2636: 
 2637: </form>
 2638: ENDUPFORM
 2639:     $result.='</td></tr></table>'."\n";
 2640:     $result.='</td></tr></table><br /><br />'."\n";
 2641:     $result.=&show_grading_menu_form($symb,$url);
 2642:     return $result;
 2643: }
 2644: 
 2645: 
 2646: sub csvuploadmap {
 2647:     my ($request)= @_;
 2648:     my ($symb,$url)=&get_symb_and_url($request);
 2649:     if (!$symb) {return '';}
 2650: 
 2651:     my $datatoken;
 2652:     if (!$ENV{'form.datatoken'}) {
 2653: 	$datatoken=&Apache::loncommon::upfile_store($request);
 2654:     } else {
 2655: 	$datatoken=$ENV{'form.datatoken'};
 2656: 	&Apache::loncommon::load_tmp_file($request);
 2657:     }
 2658:     my @records=&Apache::loncommon::upfile_record_sep();
 2659:     &csvuploadmap_header($request,$symb,$url,$datatoken,$#records+1);
 2660:     my ($i,$keyfields);
 2661:     if (@records) {
 2662: 	my @fields=&csvupload_fields($url);
 2663: 
 2664: 	if ($ENV{'form.upfile_associate'} eq 'reverse') {	
 2665: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 2666: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 2667: 							  \@fields);
 2668: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 2669: 	    chop($keyfields);
 2670: 	} else {
 2671: 	    unshift(@fields,['none','']);
 2672: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 2673: 							    \@fields);
 2674: 	    my %sone=&Apache::loncommon::record_sep($records[0]);
 2675: 	    $keyfields=join(',',sort(keys(%sone)));
 2676: 	}
 2677:     }
 2678:     &csvuploadmap_footer($request,$i,$keyfields);
 2679:     $request->print(&show_grading_menu_form($symb,$url));
 2680: 
 2681:     return '';
 2682: }
 2683: 
 2684: sub csvuploadassign {
 2685:     my ($request)= @_;
 2686:     my ($symb,$url)=&get_symb_and_url($request);
 2687:     if (!$symb) {return '';}
 2688:     &Apache::loncommon::load_tmp_file($request);
 2689:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 2690:     my @keyfields = split(/\,/,$ENV{'form.keyfields'});
 2691:     my %fields=();
 2692:     for (my $i=0; $i<=$ENV{'form.nfields'}; $i++) {
 2693: 	if ($ENV{'form.upfile_associate'} eq 'reverse') {
 2694: 	    if ($ENV{'form.f'.$i} ne 'none') {
 2695: 		$fields{$keyfields[$i]}=$ENV{'form.f'.$i};
 2696: 	    }
 2697: 	} else {
 2698: 	    if ($ENV{'form.f'.$i} ne 'none') {
 2699: 		$fields{$ENV{'form.f'.$i}}=$keyfields[$i];
 2700: 	    }
 2701: 	}
 2702:     }
 2703:     $request->print('<h3>Assigning Grades</h3>');
 2704:     my $courseid=$ENV{'request.course.id'};
 2705:     my ($classlist) = &getclasslist('all',0);
 2706:     my @notallowed;
 2707:     my @skipped;
 2708:     my $countdone=0;
 2709:     foreach my $grade (@gradedata) {
 2710: 	my %entries=&Apache::loncommon::record_sep($grade);
 2711: 	my $username=$entries{$fields{'username'}};
 2712: 	my $domain=$entries{$fields{'domain'}};
 2713: 	if (!exists($$classlist{"$username:$domain"})) {
 2714: 	    push(@skipped,"$username:$domain");
 2715: 	    next;
 2716: 	}
 2717: 	my $usec=$classlist->{"$username:$domain"}[5];
 2718: 	if (!&canmodify($usec)) {
 2719: 	    push(@notallowed,"$username:$domain");
 2720: 	    next;
 2721: 	}
 2722: 	my %grades;
 2723: 	foreach my $dest (keys(%fields)) {
 2724: 	    if ($dest eq 'username' || $dest eq 'domain') { next; }
 2725: 	    if ($entries{$fields{$dest}} eq '') { next; }
 2726: 	    my $store_key=$dest;
 2727: 	    $store_key=~s/^stores/resource/;
 2728: 	    $store_key=~s/_/\./g;
 2729: 	    $grades{$store_key}=$entries{$fields{$dest}};
 2730: 	}
 2731: 	$grades{"resource.regrader"}="$ENV{'user.name'}:$ENV{'user.domain'}";
 2732: 	&Apache::lonnet::cstore(\%grades,$symb,$ENV{'request.course.id'},
 2733: 				$domain,$username);
 2734: 	$request->print('.');
 2735: 	$request->rflush();
 2736: 	$countdone++;
 2737:     }
 2738:     $request->print("<br />Stored $countdone students\n");
 2739:     if (@skipped) {
 2740: 	$request->print('<p<font size="+1"><b>Skipped Students</b></font></p>');
 2741: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 2742:     }
 2743:     if (@notallowed) {
 2744: 	$request->print('<p><font size="+1" color="red"><b>Students Not Allowed to Modify</b></font></p>');
 2745: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 2746:     }
 2747:     $request->print("<br />\n");
 2748:     $request->print(&show_grading_menu_form($symb,$url));
 2749:     return '';
 2750: }
 2751: #------------- end of section for handling csv file upload ---------
 2752: #
 2753: #-------------------------------------------------------------------
 2754: #
 2755: #-------------- Next few routines handle grading by page/sequence
 2756: #
 2757: #--- Select a page/sequence and a student to grade
 2758: sub pickStudentPage {
 2759:     my ($request) = shift;
 2760: 
 2761:     $request->print(<<LISTJAVASCRIPT);
 2762: <script type="text/javascript" language="javascript">
 2763: 
 2764: function checkPickOne(formname) {
 2765:     if (radioSelection(formname.student) == null) {
 2766: 	alert("Please select the student you wish to grade.");
 2767: 	return;
 2768:     }
 2769:     ptr = pullDownSelection(formname.selectpage);
 2770:     formname.page.value = formname["page"+ptr].value;
 2771:     formname.title.value = formname["title"+ptr].value;
 2772:     formname.submit();
 2773: }
 2774: 
 2775: </script>
 2776: LISTJAVASCRIPT
 2777:     &commonJSfunctions($request);
 2778:     my ($symb,$url) = &get_symb_and_url($request);
 2779:     my $cdom      = $ENV{"course.$ENV{'request.course.id'}.domain"};
 2780:     my $cnum      = $ENV{"course.$ENV{'request.course.id'}.num"};
 2781:     my $getsec    = $ENV{'form.section'} eq '' ? 'all' : $ENV{'form.section'};
 2782: 
 2783:     my $result='<h3><font color="#339933">&nbsp;'.
 2784: 	'Manual Grading by Page or Sequence</font></h3>';
 2785: 
 2786:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 2787:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
 2788:     my ($titles,$symbx) = &getSymbMap($request);
 2789:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 2790: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 2791: #    my $type=($curpage =~ /\.(page|sequence)/);
 2792:     my $ctr=0;
 2793:     foreach (@$titles) {
 2794: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 2795: 	$result.='<option value="'.$ctr.'" '.
 2796: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="on"' : '').
 2797: 	    '>'.$showtitle.'</option>'."\n";
 2798: 	$ctr++;
 2799:     }
 2800:     $result.= '</select>'."<br>\n";
 2801:     $ctr=0;
 2802:     foreach (@$titles) {
 2803: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 2804: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 2805: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 2806: 	$ctr++;
 2807:     }
 2808:     $result.='<input type="hidden" name="page" />'."\n".
 2809: 	'<input type="hidden" name="title" />'."\n";
 2810: 
 2811:     $result.='&nbsp;<b>View Problems Text: </b><input type="radio" name="vProb" value="no" checked="on" /> no '."\n".
 2812: 	'<input type="radio" name="vProb" value="yes" /> yes '."<br>\n";
 2813: 
 2814:     $result.='&nbsp;<b>Submission Details: </b>'.
 2815: 	'<input type="radio" name="lastSub" value="none" /> none'."\n".
 2816: 	'<input type="radio" name="lastSub" value="datesub" checked /> by dates and submissions'."\n".
 2817: 	'<input type="radio" name="lastSub" value="all" /> all details'."\n";
 2818: 
 2819:     $result.='<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
 2820: 	'<input type="hidden" name="Status"  value="'.$ENV{'form.Status'}.'" />'."\n".
 2821: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 2822: 	'<input type="hidden" name="url"     value="'.$url.'" />'."\n".
 2823: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
 2824: 	'<input type="hidden" name="saveState" value="'.$ENV{'form.saveState'}.'" />'."<br />\n";
 2825: 
 2826:     $result.='&nbsp;<input type="button" '.
 2827: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
 2828: 
 2829:     $request->print($result);
 2830: 
 2831:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br>'.
 2832: 	'<table border="0"><tr><td bgcolor="#777777">'.
 2833: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 2834: 	'<td align="right">&nbsp;<b>No.</b></td>'.
 2835: 	'<td>'.&nameUserString('header').'</td>'.
 2836: 	'<td align="right">&nbsp;<b>No.</b></td>'.
 2837: 	'<td>'.&nameUserString('header').'</td></tr>';
 2838:  
 2839:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 2840:     my $ptr = 1;
 2841:     foreach my $student (sort {lc($$fullname{$a}) cmp lc($$fullname{$b}) } keys %$fullname) {
 2842: 	my ($uname,$udom) = split(/:/,$student);
 2843: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
 2844: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 2845: 	$studentTable.='<td>&nbsp;<input type="radio" name="student" value="'.$student.'" /> '
 2846: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."\n";
 2847: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
 2848: 	$ptr++;
 2849:     }
 2850:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;' if ($ptr%2 == 0);
 2851:     $studentTable.='</td></tr></table></td></tr></table>'."\n";
 2852:     $studentTable.='<input type="button" '.
 2853: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
 2854: 
 2855:     $studentTable.=&show_grading_menu_form($symb,$url);
 2856:     $request->print($studentTable);
 2857: 
 2858:     return '';
 2859: }
 2860: 
 2861: sub getSymbMap {
 2862:     my ($request) = @_;
 2863:     my $navmap = Apache::lonnavmaps::navmap->new();
 2864: 
 2865:     my %symbx = ();
 2866:     my @titles = ();
 2867:     my $minder = 0;
 2868: 
 2869:     # Gather every sequence that has problems.
 2870:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); }, 1);
 2871:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 2872: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 2873: 	    my $title = $minder.'.'.$sequence->compTitle();
 2874: 	    push @titles, $title; # minder in case two titles are identical
 2875: 	    $symbx{$title} = $sequence->symb();
 2876: 	    $minder++;
 2877: 	}
 2878:     }
 2879: 
 2880:     $navmap->untieHashes();
 2881:     return \@titles,\%symbx;
 2882: }
 2883: 
 2884: #
 2885: #--- Displays a page/sequence w/wo problems, w/wo submissions
 2886: sub displayPage {
 2887:     my ($request) = shift;
 2888: 
 2889:     my ($symb,$url) = &get_symb_and_url($request);
 2890:     my $cdom      = $ENV{"course.$ENV{'request.course.id'}.domain"};
 2891:     my $cnum      = $ENV{"course.$ENV{'request.course.id'}.num"};
 2892:     my $getsec    = $ENV{'form.section'} eq '' ? 'all' : $ENV{'form.section'};
 2893:     my $pageTitle = $ENV{'form.page'};
 2894:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 2895:     my ($uname,$udom) = split(/:/,$ENV{'form.student'});
 2896:     my $usec=$classlist->{$ENV{'form.student'}}[5];
 2897:     if (!&canview($usec)) {
 2898: 	$request->print('<font color="red">Unable to view requested student.('.$ENV{'form.student'}.')</font>');
 2899: 	$request->print(&show_grading_menu_form($symb,$url));
 2900: 	return;
 2901:     }
 2902:     my $result='<h3><font color="#339933">&nbsp;'.$ENV{'form.title'}.'</font></h3>';
 2903:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$ENV{'form.student'}},$uname,$udom).
 2904: 	'</h3>'."\n";
 2905:     &sub_page_js($request);
 2906:     $request->print($result);
 2907: 
 2908:     my $navmap = Apache::lonnavmaps::navmap->new();
 2909:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($ENV{'form.page'});
 2910:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 2911: 
 2912:     my $iterator = $navmap->getIterator($map->map_start(),
 2913: 					$map->map_finish());
 2914: 
 2915:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 2916: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 2917: 	'<input type="hidden" name="fullname" value="'.$$fullname{$ENV{'form.student'}}.'" />'."\n".
 2918: 	'<input type="hidden" name="student" value="'.$ENV{'form.student'}.'" />'."\n".
 2919: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 2920: 	'<input type="hidden" name="title"   value="'.$ENV{'form.title'}.'" />'."\n".
 2921: 	'<input type="hidden" name="url"     value="'.$url.'" />'."\n".
 2922: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
 2923: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 2924: 	'<input type="hidden" name="saveState" value="'.$ENV{'form.saveState'}.'" />'."\n";
 2925: 
 2926:     my $checkIcon = '<img src="'.$request->dir_config('lonIconsURL').
 2927: 	'/check.gif" height="16" border="0" />';
 2928: 
 2929:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
 2930: 	' symbol.'."\n".
 2931: 	'<table border="0"><tr><td bgcolor="#777777">'.
 2932: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 2933: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
 2934: 	'<td><b>&nbsp;'.($ENV{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
 2935: 
 2936:     my ($depth,$question) = (1,1);
 2937:     $iterator->next(); # skip the first BEGIN_MAP
 2938:     my $curRes = $iterator->next(); # for "current resource"
 2939:     while ($depth > 0) {
 2940:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 2941:         if($curRes == $iterator->END_MAP) { $depth--; }
 2942: 
 2943:         if (ref($curRes) && $curRes->is_problem()) {
 2944: 	    my $parts = $curRes->parts();
 2945:             my $title = $curRes->compTitle();
 2946: 	    my $symbx = $curRes->symb();
 2947: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$question.
 2948: 		(scalar(@{$parts}) == 1 ? '' : '<br>('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
 2949: 	    $studentTable.='<td valign="top">';
 2950: 	    if ($ENV{'form.vProb'} eq 'yes' ) {
 2951: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 2952: 					     undef,'both');
 2953: 	    } else {
 2954: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$ENV{'request.course.id'});
 2955: 		$companswer =~ s|<form(.*?)>||g;
 2956: 		$companswer =~ s|</form>||g;
 2957: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 2958: #		    $companswer =~ s/$1/ /ms;
 2959: #		    $request->print('match='.$1."<br>\n");
 2960: #		}
 2961: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 2962: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br>&nbsp;<b>Correct answer:</b><br>'.$companswer;
 2963: 	    }
 2964: 
 2965: 	    my %record = &Apache::lonnet::restore($symbx,$ENV{'request.course.id'},$udom,$uname);
 2966: 
 2967: 	    if ($ENV{'form.lastSub'} eq 'datesub') {
 2968: 		if ($record{'version'} eq '') {
 2969: 		    $studentTable.='<br />&nbsp;<font color="red">No recorded submission for this problem</font><br />';
 2970: 		} else {
 2971: 		    my %responseType = ();
 2972: 		    foreach my $partid (@{$parts}) {
 2973: 			$responseType{$partid} = $curRes->responseType($partid);
 2974: 		    }
 2975: 		    $studentTable.= &displaySubByDates(\$symbx,\%record,$parts,\%responseType,$checkIcon);
 2976: 		}
 2977: 	    } elsif ($ENV{'form.lastSub'} eq 'all') {
 2978: 		my $last = ($ENV{'form.lastSub'} eq 'last' ? 'last' : '');
 2979: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 2980: 									$ENV{'request.course.id'},
 2981: 									'','.submission');
 2982:  
 2983: 	    }
 2984: 	    if (&canmodify($usec)) {
 2985: 		foreach my $partid (@{$parts}) {
 2986: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 2987: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 2988: 		    $question++;
 2989: 		}
 2990: 	    }
 2991: 	    $studentTable.='</td></tr>';
 2992: 
 2993: 	}
 2994:         $curRes = $iterator->next();
 2995:     }
 2996: 
 2997:     $navmap->untieHashes();
 2998: 
 2999:     $studentTable.='</td></tr></table></td></tr></table>'."\n".
 3000: 	'<input type="button" value="Save" '.
 3001: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" TARGET=_self />'.
 3002: 	'</form>'."\n";
 3003:     $studentTable.=&show_grading_menu_form($symb,$url);
 3004:     $request->print($studentTable);
 3005: 
 3006:     return '';
 3007: }
 3008: 
 3009: sub displaySubByDates {
 3010:     my ($symbx,$record,$parts,$responseType,$checkIcon) = @_;
 3011:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
 3012: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
 3013: 	'<td><b>Date/Time</b></td>'.
 3014: 	'<td><b>Submission</b></td>'.
 3015: 	'<td><b>Status&nbsp;</b></td></tr>';
 3016:     my ($version);
 3017:     my %mark;
 3018:     $mark{'correct_by_student'} = $checkIcon;
 3019:     return '<br />&nbsp;<font color="red">Nothing submitted - no attempts</font><br />' 
 3020: 	if (!exists($$record{'1:timestamp'}));
 3021:     for ($version=1;$version<=$$record{'version'};$version++) {
 3022: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
 3023: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
 3024: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 3025: 	my @displaySub = ();
 3026: 	foreach my $partid (@{$parts}) {
 3027: 	    my @matchKey = grep /^resource\.$partid\..*?\.submission$/,@versionKeys;
 3028: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 3029: 	    $displaySub[0].=(exists $$record{$version.':'.$matchKey[0]}) ? 
 3030: 		'<b>Part&nbsp;'.$partid.'&nbsp;'.
 3031: 		($$record{"$version:resource.$partid.tries"} eq '' ? 'Trial&nbsp;not&nbsp;counted' :
 3032: 		 'Trial&nbsp;'.$$record{"$version:resource.$partid.tries"}).'</b>&nbsp; '.
 3033: 		 &cleanRecord($$record{$version.':'.$matchKey[0]},$$responseType{$partid},$$symbx).'<br />' : '';
 3034: 	    $displaySub[1].=(exists $$record{"$version:resource.$partid.award"}) ?
 3035: 		'<b>Part&nbsp;'.$partid.'</b> &nbsp;'.
 3036: 		lc($$record{"$version:resource.$partid.award"}).' '.
 3037: 		$mark{$$record{"$version:resource.$partid.solved"}}.'<br />' : '';
 3038: 	    $displaySub[2].=(exists $$record{"$version:resource.$partid.regrader"}) ?
 3039: 		$$record{"$version:resource.$partid.regrader"}.' (<b>Part:</b> '.$partid.')' : '';
 3040: 	}
 3041: 	$displaySub[2].=(exists $$record{"$version:resource.regrader"}) ?
 3042: 	    $$record{"$version:resource.regrader"} : ''; # needed because old essay regrader has not parts info
 3043: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1].
 3044: 	    ($displaySub[2] eq '' ? '' : 'Manually graded by '.$displaySub[2]).'&nbsp;</td></tr>';
 3045:     }
 3046:     $studentTable.='</table></td></tr></table>';
 3047:     return $studentTable;
 3048: }
 3049: 
 3050: sub updateGradeByPage {
 3051:     my ($request) = shift;
 3052: 
 3053:     my $cdom      = $ENV{"course.$ENV{'request.course.id'}.domain"};
 3054:     my $cnum      = $ENV{"course.$ENV{'request.course.id'}.num"};
 3055:     my $getsec    = $ENV{'form.section'} eq '' ? 'all' : $ENV{'form.section'};
 3056:     my $pageTitle = $ENV{'form.page'};
 3057:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 3058:     my ($uname,$udom) = split(/:/,$ENV{'form.student'});
 3059:     my $usec=$classlist->{$ENV{'form.student'}}[5];
 3060:     if (!&canmodify($usec)) {
 3061: 	$request->print('<font color="red">Unable to modify requested student.('.$ENV{'form.student'}.'</font>');
 3062: 	$request->print(&show_grading_menu_form($ENV{'form.symb'},$ENV{'form.url'}));
 3063: 	return;
 3064:     }
 3065:     my $result='<h3><font color="#339933">&nbsp;'.$ENV{'form.title'}.'</font></h3>';
 3066:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$ENV{'form.fullname'},$uname,$udom).
 3067: 	'</h3>'."\n";
 3068: 
 3069:     $request->print($result);
 3070: 
 3071:     my $navmap = Apache::lonnavmaps::navmap->new();
 3072:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $ENV{'form.page'});
 3073:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 3074: 
 3075:     my $iterator = $navmap->getIterator($map->map_start(),
 3076: 					$map->map_finish());
 3077: 
 3078:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
 3079: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 3080: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
 3081: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
 3082: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
 3083: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
 3084: 
 3085:     $iterator->next(); # skip the first BEGIN_MAP
 3086:     my $curRes = $iterator->next(); # for "current resource"
 3087:     my ($depth,$question,$changeflag)= (1,1,0);
 3088:     while ($depth > 0) {
 3089:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 3090:         if($curRes == $iterator->END_MAP) { $depth--; }
 3091: 
 3092:         if (ref($curRes) && $curRes->is_problem() && !$curRes->randomout) {
 3093: 	    my $parts = $curRes->parts();
 3094:             my $title = $curRes->compTitle();
 3095: 	    my $symbx = $curRes->symb();
 3096: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$question.
 3097: 		(scalar(@{$parts}) == 1 ? '' : '<br>('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
 3098: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 3099: 
 3100: 	    my %newrecord=();
 3101: 	    my @displayPts=();
 3102: 	    foreach my $partid (@{$parts}) {
 3103: 		my $newpts = $ENV{'form.GD_BOX'.$question.'_'.$partid};
 3104: 		my $oldpts = $ENV{'form.oldpts'.$question.'_'.$partid};
 3105: 
 3106: 		my $wgt = $ENV{'form.WGT'.$question.'_'.$partid} != 0 ? 
 3107: 		    $ENV{'form.WGT'.$question.'_'.$partid} : 1;
 3108: 		my $partial = $newpts/$wgt;
 3109: 		my $score;
 3110: 		if ($partial > 0) {
 3111: 		    $score = 'correct_by_override';
 3112: 		} elsif ($newpts ne '') { #empty is taken as 0
 3113: 		    $score = 'incorrect_by_override';
 3114: 		}
 3115: 		my $dropMenu = $ENV{'form.GD_SEL'.$question.'_'.$partid};
 3116: 		if ($dropMenu eq 'excused') {
 3117: 		    $partial = '';
 3118: 		    $score = 'excused';
 3119: 		} elsif ($dropMenu eq 'reset status'
 3120: 			 && $ENV{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 3121: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 3122: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 3123: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 3124: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 3125: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$ENV{'user.name'}:$ENV{'user.domain'}";
 3126: 		    $changeflag++;
 3127: 		    $newpts = '';
 3128: 		}
 3129: 
 3130: 		my $oldstatus = $ENV{'form.solved'.$question.'_'.$partid};
 3131: 		$displayPts[0].='&nbsp;<b>Part</b> '.$partid.' = '.
 3132: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 3133: 		    '&nbsp;<br>';
 3134: 		$displayPts[1].='&nbsp;<b>Part</b> '.$partid.' = '.
 3135: 		     (($score eq 'excused') ? 'excused' : $newpts).
 3136: 		    '&nbsp;<br>';
 3137: 
 3138: 		$question++;
 3139: 		next if ($dropMenu eq 'reset status' || ($newpts == $oldpts && $score ne 'excused'));
 3140: 
 3141: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 3142: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 3143: 		$newrecord{'resource.'.$partid.'.regrader'} = "$ENV{'user.name'}:$ENV{'user.domain'}"
 3144: 		    if (scalar(keys(%newrecord)) > 0);
 3145: 
 3146: 		$changeflag++;
 3147: 	    }
 3148: 	    if (scalar(keys(%newrecord)) > 0) {
 3149: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$ENV{'request.course.id'},
 3150: 					$udom,$uname);
 3151: 	    }
 3152: 
 3153: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 3154: 		'<td valign="top">'.$displayPts[1].'</td>'.
 3155: 		'</tr>';
 3156: 
 3157: 	}
 3158:         $curRes = $iterator->next();
 3159:     }
 3160: 
 3161:     $navmap->untieHashes();
 3162: 
 3163:     $studentTable.='</td></tr></table></td></tr></table>';
 3164:     $studentTable.=&show_grading_menu_form($ENV{'form.symb'},$ENV{'form.url'});
 3165:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
 3166: 		  'The scores were changed for '.
 3167: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
 3168:     $request->print($grademsg.$studentTable);
 3169: 
 3170:     return '';
 3171: }
 3172: 
 3173: #-------- end of section for handling grading by page/sequence ---------
 3174: #
 3175: #-------------------------------------------------------------------
 3176: 
 3177: #--------------------Scantron Grading-----------------------------------
 3178: #
 3179: #------ start of section for handling grading by page/sequence ---------
 3180: 
 3181: sub defaultFormData {
 3182:     my ($symb,$url)=@_;
 3183:     return '
 3184:       <input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
 3185:      '<input type="hidden" name="url"     value="'.$url.'" />'."\n".
 3186:      '<input type="hidden" name="saveState" value="'.$ENV{'form.saveState'}.'" />'."\n".
 3187:      '<input type="hidden" name="probTitle" value="'.$ENV{'form.probTitle'}.'" />'."\n";
 3188: }
 3189: 
 3190: sub getSequenceDropDown {
 3191:     my ($request,$symb)=@_;
 3192:     my $result='<select name="selectpage">'."\n";
 3193:     my ($titles,$symbx) = &getSymbMap($request);
 3194:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 3195:     my $ctr=0;
 3196:     foreach (@$titles) {
 3197: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 3198: 	$result.='<option value="'.$$symbx{$_}.'" '.
 3199: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="on"' : '').
 3200: 	    '>'.$showtitle.'</option>'."\n";
 3201: 	$ctr++;
 3202:     }
 3203:     $result.= '</select>';
 3204:     return $result;
 3205: }
 3206: 
 3207: sub scantron_uploads {
 3208:     if (!-e $Apache::lonnet::perlvar{'lonScansDir'}) { return ''};
 3209:     my $result=	'<select name="scantron_selectfile">';
 3210:     opendir(DIR,$Apache::lonnet::perlvar{'lonScansDir'});
 3211:     my @files=sort(readdir(DIR));
 3212:     foreach my $filename (@files) {
 3213: 	if ($filename eq '.' or $filename eq '..') { next; }
 3214: 	$result.="<option>$filename</option>\n";
 3215:     }
 3216:     closedir(DIR);
 3217:     $result.="</select>";
 3218:     return $result;
 3219: }
 3220: 
 3221: sub scantron_scantab {
 3222:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 3223:     my $result='<select name="scantron_format">'."\n";
 3224:     foreach my $line (<$fh>) {
 3225: 	my ($name,$descrip)=split(/:/,$line);
 3226: 	if ($name =~ /^\#/) { next; }
 3227: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 3228:     }
 3229:     $result.='</select>'."\n";
 3230: 
 3231:     return $result;
 3232: }
 3233: 
 3234: sub scantron_selectphase {
 3235:     my ($r) = @_;
 3236:     my ($symb,$url)=&get_symb_and_url($r);
 3237:     if (!$symb) {return '';}
 3238:     my $sequence_selector=&getSequenceDropDown($r,$symb);
 3239:     my $default_form_data=&defaultFormData($symb,$url);
 3240:     my $grading_menu_button=&show_grading_menu_form($symb,$url);
 3241:     my $file_selector=&scantron_uploads();
 3242:     my $format_selector=&scantron_scantab();
 3243:     my $result;
 3244:     $result.= <<SCANTRONFORM;
 3245: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantro_process">
 3246:   <input type="hidden" name="command" value="scantron_validate" />
 3247:   $default_form_data
 3248:   <table width="100%" border="0">
 3249:     <tr>
 3250:       <td bgcolor="#777777">
 3251:         <table width="100%" border="0">
 3252:           <tr bgcolor="#e6ffff">
 3253:             <td>
 3254:               &nbsp;<b>Specify file location and which Folder/Sequence to grade</b>
 3255:             </td>
 3256:           </tr>
 3257:           <tr bgcolor="#ffffe6">
 3258:             <td>
 3259:                Sequence to grade: $sequence_selector
 3260: 	    </td>
 3261:           </tr>
 3262:           <tr bgcolor="#ffffe6">
 3263:             <td>
 3264: 		Filename of scoring office file: $file_selector
 3265: 	    </td>
 3266:           </tr>
 3267:           <tr bgcolor="#ffffe6">
 3268:             <td>
 3269:               Format of data file: $format_selector
 3270: 	    </td>
 3271:           </tr>
 3272:         </table>
 3273:       </td>
 3274:     </tr>
 3275:   </table>
 3276:   <input type="submit" value="Validate Scantron Records" />
 3277: </form>
 3278: $grading_menu_button
 3279: SCANTRONFORM
 3280: 
 3281:     return $result;
 3282: }
 3283: 
 3284: sub get_scantron_config {
 3285:     my ($which) = @_;
 3286:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 3287:     my %config;
 3288:     foreach my $line (<$fh>) {
 3289: 	my ($name,$descrip)=split(/:/,$line);
 3290: 	if ($name ne $which ) { next; }
 3291: 	chomp($line);
 3292: 	my @config=split(/:/,$line);
 3293: 	$config{'name'}=$config[0];
 3294: 	$config{'description'}=$config[1];
 3295: 	$config{'CODElocation'}=$config[2];
 3296: 	$config{'CODEstart'}=$config[3];
 3297: 	$config{'CODElength'}=$config[4];
 3298: 	$config{'IDstart'}=$config[5];
 3299: 	$config{'IDlength'}=$config[6];
 3300: 	$config{'Qstart'}=$config[7];
 3301: 	$config{'Qlength'}=$config[8];
 3302: 	$config{'Qoff'}=$config[9];
 3303: 	$config{'Qon'}=$config[10];
 3304: 	last;
 3305:     }
 3306:     return %config;
 3307: }
 3308: 
 3309: sub username_to_idmap {
 3310:     my ($classlist)= @_;
 3311:     my %idmap;
 3312:     foreach my $student (keys(%$classlist)) {
 3313: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 3314: 	    $student;
 3315:     }
 3316:     return %idmap;
 3317: }
 3318: 
 3319: sub scantron_parse_scanline {
 3320:     my ($line,$scantron_config)=@_;
 3321:     my %record;
 3322:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);
 3323:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);
 3324:     if ($$scantron_config{'CODElocation'} ne 0) {
 3325: 	if ($$scantron_config{'CODElocation'} < 0) {
 3326: 	    $record{'scantron.CODE'}=substr($data,$$scantron_config{'CODEstart'}-1,
 3327: 					    $$scantron_config{'CODElength'});
 3328: 	} else {
 3329: 	    #FIXME interpret first N questions
 3330: 	}
 3331:     }
 3332:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 3333: 				  $$scantron_config{'IDlength'});
 3334:     my @alphabet=('A'..'Z');
 3335:     my $questnum=0;
 3336:     while ($questions) {
 3337: 	$questnum++;
 3338: 	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
 3339: 	substr($questions,0,$$scantron_config{'Qlength'})='';
 3340: 	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
 3341: 	my (@array)=split(/$$scantron_config{'Qon'}/,$currentquest);
 3342: 	if (scalar(@array) gt 2) {
 3343: 	    #FIXME do something intelligent with double bubbles
 3344: 	    Apache->request->print("<br ><b>Wha!!!</b> <pre>".scalar(@array).
 3345: 				   '-'.$currentquest.'-'.$questnum.'</pre><br />');
 3346: 	}
 3347: 	if (length($array[0]) eq $$scantron_config{'Qlength'}) {
 3348: 	    $record{"scantron.$questnum.answer"}='';
 3349: 	} else {
 3350: 	    $record{"scantron.$questnum.answer"}=$alphabet[length($array[0])];
 3351: 	}
 3352:     }
 3353:     $record{'scantron.maxquest'}=$questnum;
 3354:     return \%record;
 3355: }
 3356: 
 3357: sub scantron_add_delay {
 3358:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 3359:     Apache->request->print('add_delay_error '.$_[2] );
 3360:     push(@$delayqueue,
 3361: 	 {'line' => $scanline, 'emsg' => $errormessage,
 3362: 	  'ecode' => $errorcode }
 3363: 	 );
 3364: }
 3365: 
 3366: sub scantron_find_student {
 3367:     my ($scantron_record,$idmap)=@_;
 3368:     my $scanID=$$scantron_record{'scantron.ID'};
 3369:     foreach my $id (keys(%$idmap)) {
 3370: 	#Apache->request->print('<pre>checking studnet -'.$id.'- againt -'.$scanID.'- </pre>');
 3371: 	if (lc($id) eq lc($scanID)) {
 3372: 	    #Apache->request->print('success');
 3373: 	    return $$idmap{$id};
 3374: 	}
 3375:     }
 3376:     return undef;
 3377: }
 3378: 
 3379: sub scantron_filter {
 3380:     my ($curres)=@_;
 3381:     if (ref($curres) && $curres->is_problem() && !$curres->randomout) {
 3382: 	return 1;
 3383:     }
 3384:     return 0;
 3385: }
 3386: 
 3387: #FIXME I think I am doing this in the wrong order, I think it would be
 3388: #better to make a several passes analyzing all of the lines in the
 3389: #file for common errors wrong/invalid PID/username duplicated
 3390: #PID/username, missing bubbles, double bubbles, missing/invalid CODE
 3391: #and then get the instructor to fix all of these errors, then grade
 3392: #the corrected one, I'll still need to catch error conditions, but
 3393: #maybe most will taken care even before we start
 3394: 
 3395: sub scantron_validate_file {
 3396:     my ($r) = @_;
 3397: }
 3398: 
 3399: sub scantron_process_students {
 3400:     my ($r) = @_;
 3401:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($ENV{'form.selectpage'});
 3402:     my ($symb,$url)=&get_symb_and_url($r);
 3403:     if (!$symb) {return '';}
 3404:     my $default_form_data=&defaultFormData($symb,$url);
 3405: 
 3406:     my %scantron_config=&get_scantron_config($ENV{'form.scantron_format'});
 3407:     my $scanlines=Apache::File->new($Apache::lonnet::perlvar{'lonScansDir'}."/$ENV{'form.scantron_selectfile'}");
 3408:     my @scanlines=<$scanlines>;
 3409:     my $classlist=&Apache::loncoursedata::get_classlist();
 3410:     my %idmap=&username_to_idmap($classlist);
 3411:     my $navmap=Apache::lonnavmaps::navmap->new();
 3412:     my $map=$navmap->getResourceByUrl($sequence);
 3413:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 3414: #    $r->print("geto ".scalar(@resources)."<br />");
 3415:     my $result= <<SCANTRONFORM;
 3416: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 3417:   <input type="hidden" name="command" value="scantron_configphase" />
 3418:   $default_form_data
 3419: SCANTRONFORM
 3420:     $r->print($result);
 3421: 
 3422:     my @delayqueue;
 3423:     my %completedstudents;
 3424:     
 3425:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,
 3426: 	           'Scantron Status','Scantron Progress',scalar(@scanlines));
 3427:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 3428: 					  'Processing first student');
 3429:     my $start=&Time::HiRes::time();
 3430:     foreach my $line (@scanlines) {
 3431: 	$r->print('<pre>line is'.$line.'</pre>');
 3432: 
 3433: 	chomp($line);
 3434: 	my $scan_record=&scantron_parse_scanline($line,\%scantron_config);
 3435: 	my ($uname,$udom);
 3436: 	unless ($uname=&scantron_find_student($scan_record,\%idmap)) {
 3437: 	    &scantron_add_delay(\@delayqueue,$line,
 3438: 				'Unable to find a student that matches',1);
 3439: 	    next;
 3440: 	}
 3441: 	if (exists $completedstudents{$uname}) {
 3442: 	    &scantron_add_delay(\@delayqueue,$line,
 3443: 				'Student '.$uname.' has multiple sheets',2);
 3444: 	    next;
 3445: 	}
 3446: 	$r->print('<pre>doing studnet'.$uname.'</pre>');
 3447: 	($uname,$udom)=split(/:/,$uname);
 3448: 	&Apache::lonnet::delenv('form.counter');
 3449: 	&Apache::lonnet::appenv(%$scan_record);
 3450: #    &Apache::lonhomework::showhash(%ENV);
 3451: #    $Apache::lonxml::debug=1;
 3452: #	&Apache::lonxml::debug("line is $line");
 3453: 	
 3454: 	    my $i=0;
 3455: 	foreach my $resource (@resources) {
 3456: 	    $i++;
 3457: 	    my $result=&Apache::lonnet::ssi($resource->src(),
 3458: 				 ('submitted'     =>'scantron',
 3459: 				  'grade_target'  =>'grade',
 3460: 				  'grade_username'=>$uname,
 3461: 				  'grade_domain'  =>$udom,
 3462: 				  'grade_courseid'=>$ENV{'request.course.id'},
 3463: 				  'grade_symb'    =>$resource->symb()));
 3464: #	    my %score=&Apache::lonnet::restore($resource->symb(),
 3465: #					       $ENV{'request.course.id'},
 3466: #					       $udom,$uname);
 3467: #	    foreach my $part ($resource->{PARTS}) {
 3468: #		if ($score{'resource.'.$part.'.solved'} =~ /^correct/) {
 3469: #		    $studentcorrect++;
 3470: #		    $totalcorrect++;
 3471: #		} else {
 3472: #		    $studentincorrect++;
 3473: #		    $totalincorrect++;
 3474: #		}
 3475: #	    }
 3476: #	    $r->print('<pre>'.
 3477: #		      $resource->symb().'-'.
 3478: #		      $resource->src().'-'.'</pre>result is'.$result);
 3479: #	    &Apache::lonhomework::showhash(%score);
 3480: 	#    if ($i eq 3) {last;}
 3481: 	}
 3482: 	$completedstudents{$uname}={'line'=>$line};
 3483:     } continue {
 3484: 	&Apache::lonnet::delenv('form.counter');
 3485: 	&Apache::lonnet::delenv('scantron\.');
 3486: 	&Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 3487: 						 'last student');
 3488: 	#last;
 3489: 	#FIXME
 3490: 	#get iterator for $sequence
 3491: 	#foreach question 'submit' the students answer to the server
 3492: 	#   through grade target {
 3493: 	#   generate data to pass back that includes grade recevied
 3494: 	#}
 3495:     }
 3496:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3497:     my $lasttime = &Time::HiRes::time()-$start;
 3498:     $r->print("<p>took $lasttime</p>");
 3499: 
 3500:     #$Apache::lonxml::debug=0;
 3501:     foreach my $delay (@delayqueue) {
 3502: 	#FIXME
 3503: 	#print out each delayed student with interface to select how
 3504: 	#  to repair student provided info
 3505: 	#Expected errors include
 3506: 	#  1 bad/no stuid/username
 3507: 	#  2 invalid bubblings
 3508: 	
 3509:     }
 3510:     #FIXME
 3511:     # if delay queue exists 2 submits one to process delayed students one
 3512:     #     to ignore delayed students, possibly saving the delay queue for later
 3513:     
 3514:     $navmap->untieHashes();
 3515: }
 3516: #-------- end of section for handling grading scantron forms -------
 3517: #
 3518: #-------------------------------------------------------------------
 3519: 
 3520: 
 3521: #-------------------------- Menu interface -------------------------
 3522: #
 3523: #--- Show a Grading Menu button - Calls the next routine ---
 3524: sub show_grading_menu_form {
 3525:     my ($symb,$url)=@_;
 3526:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 3527: 	'<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
 3528: 	'<input type="hidden" name="url" value="'.$url.'" />'."\n".
 3529: 	'<input type="hidden" name="saveState"  value="'.$ENV{'form.saveState'}.'" />'."\n".
 3530: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 3531: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
 3532: 	'</form>'."\n";
 3533:     return $result;
 3534: }
 3535: 
 3536: # -- Retrieve choices for grading form
 3537: sub savedState {
 3538:     my %savedState = ();
 3539:     if ($ENV{'form.saveState'}) {
 3540: 	foreach (split(/:/,$ENV{'form.saveState'})) {
 3541: 	    my ($key,$value) = split(/=/,$_,2);
 3542: 	    $savedState{$key} = $value;
 3543: 	}
 3544:     }
 3545:     return \%savedState;
 3546: }
 3547: 
 3548: #--- Displays the main menu page -------
 3549: sub gradingmenu {
 3550:     my ($request) = @_;
 3551:     my ($symb,$url)=&get_symb_and_url($request);
 3552:     if (!$symb) {return '';}
 3553:     my $probTitle = &Apache::lonnet::gettitle($symb);
 3554: 
 3555:     $request->print(<<GRADINGMENUJS);
 3556: <script type="text/javascript" language="javascript">
 3557:     function checkChoice(formname,val,cmdx) {
 3558: 	if (val <= 2) {
 3559: 	    var cmd = radioSelection(formname.radioChoice);
 3560: 	    var cmdsave = cmd;
 3561: 	} else {
 3562: 	    cmd = cmdx;
 3563: 	    cmdsave = 'submission';
 3564: 	}
 3565: 	formname.command.value = cmd;
 3566: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 3567: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 3568: 	if (val < 5) formname.submit();
 3569: 	if (val == 5) {
 3570: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 3571: 	    formname.submit();
 3572: 	}
 3573:     }
 3574: 
 3575:     function checkReceiptNo(formname,nospace) {
 3576: 	var receiptNo = formname.receipt.value;
 3577: 	var checkOpt = false;
 3578: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 3579: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 3580: 	if (checkOpt) {
 3581: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 3582: 	    formname.receipt.value = "";
 3583: 	    formname.receipt.focus();
 3584: 	    return false;
 3585: 	}
 3586: 	return true;
 3587:     }
 3588: </script>
 3589: GRADINGMENUJS
 3590:     &commonJSfunctions($request);
 3591:     my $result='<h3>&nbsp;<font color="#339933">Manual Grading/View Submission</font></h3>';
 3592:     my ($table,undef,$hdgrade) = &showResourceInfo($url,$probTitle);
 3593:     $result.=$table;
 3594:     my (undef,$sections) = &getclasslist('all','0');
 3595:     my $savedState = &savedState();
 3596:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 3597:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 3598:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 3599:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 3600: 
 3601:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 3602: 	'<input type="hidden" name="symb"        value="'.$symb.'" />'."\n".
 3603: 	'<input type="hidden" name="url"         value="'.$url.'" />'."\n".
 3604: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 3605: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 3606: 	'<input type="hidden" name="command"     value="" />'."\n".
 3607: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 3608: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 3609: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 3610: 
 3611:     $result.='<table width="100%" border=0><tr><td bgcolor=#777777>'."\n".
 3612: 	'<table width=100% border=0><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
 3613: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
 3614: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
 3615: 
 3616:     $result.='<table width="100%" border=0>';
 3617:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
 3618: 	'&nbsp;Select Section: <select name="section">'."\n";
 3619:     if (ref($sections)) {
 3620: 	foreach (sort (@$sections)) {$result.='<option value="'.$_.'" '.
 3621: 					 ($saveSec eq $_ ? 'selected="on"' : '').'>'.$_.'</option>'."\n";}
 3622:     }
 3623:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="on"' : ''). '>all</select> &nbsp; ';
 3624: 
 3625:     $result.='Student Status:</b>'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
 3626: 
 3627:     if (ref($sections)) {
 3628: 	$result.='&nbsp;(Section "no" implies the students were not assigned a section.)<br />' 
 3629: 	    if (grep /no/,@$sections);
 3630:     }
 3631:     $result.='</td></tr>';
 3632: 
 3633:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
 3634: 	'<input type="radio" name="radioChoice" value="submission" '.
 3635: 	($saveCmd eq 'submission' ? 'checked' : '').'> '.'<b>Current Resource:</b> For one or more students '.
 3636: 	'<select name="submitonly">'.
 3637: 	'<option value="yes" '.
 3638: 	($saveSub eq 'yes' ? 'selected="on"' : '').'>with submissions</option>'.
 3639: 	'<option value="graded" '.
 3640: 	($saveSub eq 'graded' ? 'selected="on"' : '').'>with ungraded submissions</option>'.
 3641: 	'<option value="all" '.
 3642: 	($saveSub eq 'all' ? 'selected="on"' : '').'>with any status</option></select></td></tr>'."\n";
 3643: 
 3644:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
 3645: 	'<input type="radio" name="radioChoice" value="viewgrades" '.
 3646: 	($saveCmd eq 'viewgrades' ? 'checked' : '').'> '.
 3647: 	'<b>Current Resource:</b> For all students in selected section or course</td></tr>'."\n";
 3648: 
 3649:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
 3650: 	'<input type="radio" name="radioChoice" value="pickStudentPage" '.
 3651: 	($saveCmd eq 'pickStudentPage' ? 'checked' : '').'> '.
 3652: 	'The <b>complete</b> set/page/sequence: For one student</td></tr>'."\n";
 3653: 
 3654:     $result.='<tr bgcolor="#ffffe6"><td><br />'.
 3655: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
 3656: 	'</td></tr></table>'."\n";
 3657: 
 3658:     $result.='</td><td valign="top">';
 3659: 
 3660:     $result.='<table width="100%" border=0>';
 3661:     $result.='<tr bgcolor="#ffffe6"><td>'.
 3662: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="Upload" />'.
 3663: 	' scores from file </td></tr>'."\n";
 3664: 
 3665:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 3666: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
 3667: 	'" value="Grade" /> scantron forms</td></tr>'."\n";
 3668: 
 3669:     if ((&Apache::lonnet::allowed('mgr',$ENV{'request.course.id'})) && ($symb)) {
 3670: 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
 3671: 	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="Verify" />'.
 3672: 	    ' submission Receipt no: '.unpack("%32C*",$Apache::lonnet::perlvar{'lonHostID'}).
 3673: 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')">'.
 3674: 	    '</td></tr>'."\n";
 3675:     } 
 3676: 
 3677:     $result.='</form></td></tr></table>'."\n".
 3678: 	'</td></tr></table>'."\n".
 3679: 	'</td></tr></table>'."\n";
 3680:     return $result;
 3681: }
 3682: 
 3683: sub handler {
 3684:     my $request=$_[0];
 3685: 
 3686:     undef(%perm);
 3687:     if ($ENV{'browser.mathml'}) {
 3688: 	&Apache::loncommon::content_type($request,'text/xml');
 3689:     } else {
 3690: 	&Apache::loncommon::content_type($request,'text/html');
 3691:     }
 3692:     $request->send_http_header;
 3693:     return '' if $request->header_only;
 3694:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 3695:     my $url=$ENV{'form.url'};
 3696:     my $symb=$ENV{'form.symb'};
 3697:     my $command=$ENV{'form.command'};
 3698:     if (!$url) {
 3699: 	my ($temp1,$temp2);
 3700: 	($temp1,$temp2,$ENV{'form.url'})=&Apache::lonnet::decode_symb($symb);
 3701: 	$url = $ENV{'form.url'};
 3702:     }
 3703:     &send_header($request);
 3704:     if ($url eq '' && $symb eq '') {
 3705: 	if ($ENV{'user.adv'}) {
 3706: 	    if (($ENV{'form.codeone'}) && ($ENV{'form.codetwo'}) &&
 3707: 		($ENV{'form.codethree'})) {
 3708: 		my $token=$ENV{'form.codeone'}.'*'.$ENV{'form.codetwo'}.'*'.
 3709: 		    $ENV{'form.codethree'};
 3710: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 3711: 		    &Apache::lonnet::checkin($token);
 3712: 		if ($tsymb) {
 3713: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 3714: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 3715: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
 3716: 					  ('grade_username' => $tuname,
 3717: 					   'grade_domain' => $tudom,
 3718: 					   'grade_courseid' => $tcrsid,
 3719: 					   'grade_symb' => $tsymb)));
 3720: 		    } else {
 3721: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 3722: 		    }
 3723: 		} else {
 3724: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 3725: 		}
 3726: 	    } else {
 3727: 		$request->print(&Apache::lonxml::tokeninputfield());
 3728: 	    }
 3729: 	}
 3730:     } else {
 3731: 	if (!($perm{'vgr'}=&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'}))) {
 3732: 	    if ($perm{'vgr'}=&Apache::lonnet::allowed('vgr',$ENV{'request.course.id'}.'/'.$ENV{'request.course.sec'})) {
 3733: 		$perm{'vgr_section'}=$ENV{'request.course.sec'};
 3734: 	    } else {
 3735: 		delete($perm{'vgr'});
 3736: 	    }
 3737: 	}
 3738: 	if (!($perm{'mgr'}=&Apache::lonnet::allowed('mgr',$ENV{'request.course.id'}))) {
 3739: 	    if ($perm{'mgr'}=&Apache::lonnet::allowed('mgr',$ENV{'request.course.id'}.'/'.$ENV{'request.course.sec'})) {
 3740: 		$perm{'mgr_section'}=$ENV{'request.course.sec'};
 3741: 	    } else {
 3742: 		delete($perm{'mgr'});
 3743: 	    }
 3744: 	}
 3745: 
 3746: 	if ($command eq 'submission' && $perm{'vgr'}) {
 3747: 	    ($ENV{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 3748: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 3749: 	    &pickStudentPage($request);
 3750: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 3751: 	    &displayPage($request);
 3752: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 3753: 	    &updateGradeByPage($request);
 3754: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 3755: 	    &processGroup($request);
 3756: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 3757: 	    $request->print(&gradingmenu($request));
 3758: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 3759: 	    $request->print(&viewgrades($request));
 3760: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 3761: 	    $request->print(&processHandGrade($request));
 3762: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 3763: 	    $request->print(&editgrades($request));
 3764: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 3765: 	    $request->print(&verifyreceipt($request));
 3766: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 3767: 	    $request->print(&upcsvScores_form($request));
 3768: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 3769: 	    $request->print(&csvupload($request));
 3770: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 3771: 	    $request->print(&csvuploadmap($request));
 3772: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'}) {
 3773: 	    if ($ENV{'form.associate'} ne 'Reverse Association') {
 3774: 		$request->print(&csvuploadassign($request));
 3775: 	    } else {
 3776: 		if ( $ENV{'form.upfile_associate'} ne 'reverse' ) {
 3777: 		    $ENV{'form.upfile_associate'} = 'reverse';
 3778: 		} else {
 3779: 		    $ENV{'form.upfile_associate'} = 'forward';
 3780: 		}
 3781: 		$request->print(&csvuploadmap($request));
 3782: 	    }
 3783: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 3784: 	    $request->print(&scantron_selectphase($request));
 3785: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 3786: 	    $request->print(&scantron_validate_file($request));
 3787: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 3788: 	    $request->print(&scantron_process_students($request));
 3789: 	} elsif ($command) {
 3790: 	    $request->print("Access Denied");
 3791: 	}
 3792:     }
 3793:     &send_footer($request);
 3794:     return '';
 3795: }
 3796: 
 3797: sub send_header {
 3798:     my ($request)= @_;
 3799:     $request->print(&Apache::lontexconvert::header());
 3800: #  $request->print("
 3801: #<script>
 3802: #remotewindow=open('','homeworkremote');
 3803: #remotewindow.close();
 3804: #</script>"); 
 3805:     $request->print(&Apache::loncommon::bodytag('Grading'));
 3806: }
 3807: 
 3808: sub send_footer {
 3809:     my ($request)= @_;
 3810:     $request->print('</body>');
 3811:     $request->print(&Apache::lontexconvert::footer());
 3812: }
 3813: 
 3814: 1;
 3815: 
 3816: __END__;

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