File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.463: download - view: text, annotated - select for diffs
Thu Oct 25 00:47:24 2007 UTC (16 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#5486, when uploading, students assigned 0 points are marked as incorrect

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.463 2007/10/25 00:47:24 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::grades;
   30: use strict;
   31: use Apache::style;
   32: use Apache::lonxml;
   33: use Apache::lonnet;
   34: use Apache::loncommon;
   35: use Apache::lonhtmlcommon;
   36: use Apache::lonnavmaps;
   37: use Apache::lonhomework;
   38: use Apache::lonpickcode;
   39: use Apache::loncoursedata;
   40: use Apache::lonmsg();
   41: use Apache::Constants qw(:common);
   42: use Apache::lonlocal;
   43: use Apache::lonenc;
   44: use String::Similarity;
   45: use LONCAPA;
   46: 
   47: use POSIX qw(floor);
   48: 
   49: 
   50: my %perm=();
   51: my %bubble_lines_per_response = ();     # no. bubble lines for each response.
   52:                                    # index is "symb.part_id"
   53: 
   54: my %first_bubble_line = ();	# First bubble line no. for each bubble.
   55: 
   56: # Save and restore the bubble lines array to the form env.
   57: 
   58: 
   59: sub save_bubble_lines {
   60:     foreach my $line (keys(%bubble_lines_per_response)) {
   61: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
   62: 	$env{"form.scantron.first_bubble_line.$line"} =
   63: 	    $first_bubble_line{$line};
   64:     }
   65: }
   66: 
   67: 
   68: sub restore_bubble_lines {
   69:     my $line = 0;
   70:     %bubble_lines_per_response = ();
   71:     while ($env{"form.scantron.bubblelines.$line"}) {
   72: 	my $value = $env{"form.scantron.bubblelines.$line"};
   73: 	$bubble_lines_per_response{$line} = $value;
   74: 	$first_bubble_line{$line}  =
   75: 	    $env{"form.scantron.first_bubble_line.$line"};
   76: 	$line++;
   77:     }
   78: 
   79: }
   80: 
   81: #  Given the parsed scanline, get the response for 
   82: #  'answer' number n:
   83: 
   84: sub get_response_bubbles {
   85:     my ($parsed_line, $response)  = @_;
   86: 
   87: 
   88:     my $bubble_line = $first_bubble_line{$response-1} +1;
   89:     my $bubble_lines= $bubble_lines_per_response{$response-1};
   90:     
   91:     my $selected = "";
   92: 
   93:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
   94: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
   95: 	$bubble_line++;
   96:     }
   97:     return $selected;
   98: }
   99: 
  100: 
  101: # ----- These first few routines are general use routines.----
  102: 
  103: # Return the number of occurences of a pattern in a string.
  104: 
  105: sub occurence_count {
  106:     my ($string, $pattern) = @_;
  107: 
  108:     my @matches = ($string =~ /$pattern/g);
  109: 
  110:     return scalar(@matches);
  111: }
  112: 
  113: 
  114: # Take a string known to have digits and convert all the
  115: # digits into letters in the range J,A..I.
  116: 
  117: sub digits_to_letters {
  118:     my ($input) = @_;
  119: 
  120:     my @alphabet = ('J', 'A'..'I');
  121: 
  122:     my @input    = split(//, $input);
  123:     my $output ='';
  124:     for (my $i = 0; $i < scalar(@input); $i++) {
  125: 	if ($input[$i] =~ /\d/) {
  126: 	    $output .= $alphabet[$input[$i]];
  127: 	} else {
  128: 	    $output .= $input[$i];
  129: 	}
  130:     }
  131:     return $output;
  132: }
  133: 
  134: #
  135: # --- Retrieve the parts from the metadata file.---
  136: sub getpartlist {
  137:     my ($symb) = @_;
  138: 
  139:     my $navmap   = Apache::lonnavmaps::navmap->new();
  140:     my $res      = $navmap->getBySymb($symb);
  141:     my $partlist = $res->parts();
  142:     my $url      = $res->src();
  143:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  144: 
  145:     my @stores;
  146:     foreach my $part (@{ $partlist }) {
  147: 	foreach my $key (@metakeys) {
  148: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  149: 	}
  150:     }
  151:     return @stores;
  152: }
  153: 
  154: # --- Get the symbolic name of a problem and the url
  155: sub get_symb {
  156:     my ($request,$silent) = @_;
  157:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  158:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  159:     if ($symb eq '') { 
  160: 	if (!$silent) {
  161: 	    $request->print("Unable to handle ambiguous references:$url:.");
  162: 	    return ();
  163: 	}
  164:     }
  165:     &Apache::lonenc::check_decrypt(\$symb);
  166:     return ($symb);
  167: }
  168: 
  169: #--- Format fullname, username:domain if different for display
  170: #--- Use anywhere where the student names are listed
  171: sub nameUserString {
  172:     my ($type,$fullname,$uname,$udom) = @_;
  173:     if ($type eq 'header') {
  174: 	return '<b>&nbsp;Fullname&nbsp;</b><span class="LC_internal_info">(Username)</span>';
  175:     } else {
  176: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  177: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  178:     }
  179: }
  180: 
  181: #--- Get the partlist and the response type for a given problem. ---
  182: #--- Indicate if a response type is coded handgraded or not. ---
  183: sub response_type {
  184:     my ($symb) = shift;
  185: 
  186:     my $navmap = Apache::lonnavmaps::navmap->new();
  187:     my $res = $navmap->getBySymb($symb);
  188:     my $partlist = $res->parts();
  189:     my %vPart = 
  190: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  191:     my (%response_types,%handgrade);
  192:     foreach my $part (@{ $partlist }) {
  193: 	next if (%vPart && !exists($vPart{$part}));
  194: 
  195: 	my @types = $res->responseType($part);
  196: 	my @ids = $res->responseIds($part);
  197: 	for (my $i=0; $i < scalar(@ids); $i++) {
  198: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  199: 	    $handgrade{$part.'_'.$ids[$i]} = 
  200: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  201: 				     '.handgrade',$symb);
  202: 	}
  203:     }
  204:     return ($partlist,\%handgrade,\%response_types);
  205: }
  206: 
  207: sub flatten_responseType {
  208:     my ($responseType) = @_;
  209:     my @part_response_id =
  210: 	map { 
  211: 	    my $part = $_;
  212: 	    map {
  213: 		[$part,$_]
  214: 		} sort(keys(%{ $responseType->{$part} }));
  215: 	} sort(keys(%$responseType));
  216:     return @part_response_id;
  217: }
  218: 
  219: sub get_display_part {
  220:     my ($partID,$symb)=@_;
  221:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  222:     if (defined($display) and $display ne '') {
  223: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
  224:     } else {
  225: 	$display=$partID;
  226:     }
  227:     return $display;
  228: }
  229: 
  230: #--- Show resource title
  231: #--- and parts and response type
  232: sub showResourceInfo {
  233:     my ($symb,$probTitle,$checkboxes) = @_;
  234:     my $col=3;
  235:     if ($checkboxes) { $col=4; }
  236:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  237:     $result .='<table border="0">';
  238:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
  239:     my %resptype = ();
  240:     my $hdgrade='no';
  241:     my %partsseen;
  242:     foreach my $partID (sort keys(%$responseType)) {
  243: 	foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
  244: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
  245: 	    my $responsetype = $responseType->{$partID}->{$resID};
  246: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
  247: 	    $result.='<tr>';
  248: 	    if ($checkboxes) {
  249: 		if (exists($partsseen{$partID})) {
  250: 		    $result.="<td>&nbsp;</td>";
  251: 		} else {
  252: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  253: 		}
  254: 		$partsseen{$partID}=1;
  255: 	    }
  256: 	    my $display_part=&get_display_part($partID,$symb);
  257: 	    $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
  258: 		$resID.'</span></td>'.
  259: 		'<td><b>Type: </b>'.$responsetype.'</td></tr>';
  260: #	    '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
  261: 	}
  262:     }
  263:     $result.='</table>'."\n";
  264:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  265: }
  266: 
  267: sub reset_caches {
  268:     &reset_analyze_cache();
  269:     &reset_perm();
  270: }
  271: 
  272: {
  273:     my %analyze_cache;
  274: 
  275:     sub reset_analyze_cache {
  276: 	undef(%analyze_cache);
  277:     }
  278: 
  279:     sub get_analyze {
  280: 	my ($symb,$uname,$udom)=@_;
  281: 	my $key = "$symb\0$uname\0$udom";
  282: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
  283: 
  284: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  285: 	$url=&Apache::lonnet::clutter($url);
  286: 	my $subresult=&Apache::lonnet::ssi($url,
  287: 					   ('grade_target' => 'analyze'),
  288: 					   ('grade_domain' => $udom),
  289: 					   ('grade_symb' => $symb),
  290: 					   ('grade_courseid' => 
  291: 					    $env{'request.course.id'}),
  292: 					   ('grade_username' => $uname));
  293: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  294: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  295: 	return $analyze_cache{$key} = \%analyze;
  296:     }
  297: 
  298:     sub get_order {
  299: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  300: 	my $analyze = &get_analyze($symb,$uname,$udom);
  301: 	return $analyze->{"$partid.$respid.shown"};
  302:     }
  303: 
  304:     sub get_radiobutton_correct_foil {
  305: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  306: 	my $analyze = &get_analyze($symb,$uname,$udom);
  307: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
  308: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  309: 		return $foil;
  310: 	    }
  311: 	}
  312:     }
  313: }
  314: 
  315: #--- Clean response type for display
  316: #--- Currently filters option/rank/radiobutton/match/essay/Task
  317: #        response types only.
  318: sub cleanRecord {
  319:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  320: 	$uname,$udom) = @_;
  321:     my $grayFont = '<span class="LC_internal_info">';
  322:     if ($response =~ /^(option|rank)$/) {
  323: 	my %answer=&Apache::lonnet::str2hash($answer);
  324: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  325: 	my ($toprow,$bottomrow);
  326: 	foreach my $foil (@$order) {
  327: 	    if ($grading{$foil} == 1) {
  328: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  329: 	    } else {
  330: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  331: 	    }
  332: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  333: 	}
  334: 	return '<blockquote><table border="1">'.
  335: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
  336: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
  337: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  338:     } elsif ($response eq 'match') {
  339: 	my %answer=&Apache::lonnet::str2hash($answer);
  340: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  341: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  342: 	my ($toprow,$middlerow,$bottomrow);
  343: 	foreach my $foil (@$order) {
  344: 	    my $item=shift(@items);
  345: 	    if ($grading{$foil} == 1) {
  346: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  347: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  348: 	    } else {
  349: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  350: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  351: 	    }
  352: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  353: 	}
  354: 	return '<blockquote><table border="1">'.
  355: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
  356: 	    '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
  357: 	    $middlerow.'</tr>'.
  358: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
  359: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  360:     } elsif ($response eq 'radiobutton') {
  361: 	my %answer=&Apache::lonnet::str2hash($answer);
  362: 	my ($toprow,$bottomrow);
  363: 	my $correct = 
  364: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  365: 	foreach my $foil (@$order) {
  366: 	    if (exists($answer{$foil})) {
  367: 		if ($foil eq $correct) {
  368: 		    $toprow.='<td><b>true</b></td>';
  369: 		} else {
  370: 		    $toprow.='<td><i>true</i></td>';
  371: 		}
  372: 	    } else {
  373: 		$toprow.='<td>false</td>';
  374: 	    }
  375: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  376: 	}
  377: 	return '<blockquote><table border="1">'.
  378: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
  379: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
  380: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  381:     } elsif ($response eq 'essay') {
  382: 	if (! exists ($env{'form.'.$symb})) {
  383: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  384: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  385: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  386: 
  387: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  388: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  389: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  390: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  391: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  392: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  393: 	}
  394: 	$answer =~ s-\n-<br />-g;
  395: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  396:     } elsif ( $response eq 'organic') {
  397: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  398: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  399: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  400: 	return $result;
  401:     } elsif ( $response eq 'Task') {
  402: 	if ( $answer eq 'SUBMITTED') {
  403: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  404: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  405: 	    return $result;
  406: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  407: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  408: 			       keys(%{$record}));
  409: 	    return join('<br />',($version,@matches));
  410: 			       
  411: 			       
  412: 	} else {
  413: 	    my $result =
  414: 		'<p>'
  415: 		.&mt('Overall result: [_1]',
  416: 		     $record->{$version."resource.$respid.$partid.status"})
  417: 		.'</p>';
  418: 	    
  419: 	    $result .= '<ul>';
  420: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  421: 			     keys(%{$record}));
  422: 	    foreach my $grade (sort(@grade)) {
  423: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  424: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  425: 				     $dim, $record->{$grade}).
  426: 			  '</li>';
  427: 	    }
  428: 	    $result.='</ul>';
  429: 	    return $result;
  430: 	}
  431:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  432: 	$answer = 
  433: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  434: 							      $answer);
  435:     }
  436:     return $answer;
  437: }
  438: 
  439: #-- A couple of common js functions
  440: sub commonJSfunctions {
  441:     my $request = shift;
  442:     $request->print(<<COMMONJSFUNCTIONS);
  443: <script type="text/javascript" language="javascript">
  444:     function radioSelection(radioButton) {
  445: 	var selection=null;
  446: 	if (radioButton.length > 1) {
  447: 	    for (var i=0; i<radioButton.length; i++) {
  448: 		if (radioButton[i].checked) {
  449: 		    return radioButton[i].value;
  450: 		}
  451: 	    }
  452: 	} else {
  453: 	    if (radioButton.checked) return radioButton.value;
  454: 	}
  455: 	return selection;
  456:     }
  457: 
  458:     function pullDownSelection(selectOne) {
  459: 	var selection="";
  460: 	if (selectOne.length > 1) {
  461: 	    for (var i=0; i<selectOne.length; i++) {
  462: 		if (selectOne[i].selected) {
  463: 		    return selectOne[i].value;
  464: 		}
  465: 	    }
  466: 	} else {
  467:             // only one value it must be the selected one
  468: 	    return selectOne.value;
  469: 	}
  470:     }
  471: </script>
  472: COMMONJSFUNCTIONS
  473: }
  474: 
  475: #--- Dumps the class list with usernames,list of sections,
  476: #--- section, ids and fullnames for each user.
  477: sub getclasslist {
  478:     my ($getsec,$filterlist,$getgroup) = @_;
  479:     my @getsec;
  480:     my @getgroup;
  481:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  482:     if (!ref($getsec)) {
  483: 	if ($getsec ne '' && $getsec ne 'all') {
  484: 	    @getsec=($getsec);
  485: 	}
  486:     } else {
  487: 	@getsec=@{$getsec};
  488:     }
  489:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  490:     if (!ref($getgroup)) {
  491: 	if ($getgroup ne '' && $getgroup ne 'all') {
  492: 	    @getgroup=($getgroup);
  493: 	}
  494:     } else {
  495: 	@getgroup=@{$getgroup};
  496:     }
  497:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
  498: 
  499:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
  500:     # Bail out if we were unable to get the classlist
  501:     return if (! defined($classlist));
  502:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
  503:     #
  504:     my %sections;
  505:     my %fullnames;
  506:     foreach my $student (keys(%$classlist)) {
  507:         my $end      = 
  508:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  509:         my $start    = 
  510:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  511:         my $id       = 
  512:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  513:         my $section  = 
  514:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  515:         my $fullname = 
  516:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  517:         my $status   = 
  518:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  519:         my $group   = 
  520:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  521: 	# filter students according to status selected
  522: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  523: 	    if (!($stu_status =~ $status)) {
  524: 		delete($classlist->{$student});
  525: 		next;
  526: 	    }
  527: 	}
  528: 	# filter students according to groups selected
  529: 	my @stu_groups = split(/,/,$group);
  530: 	if (@getgroup) {
  531: 	    my $exclude = 1;
  532: 	    foreach my $grp (@getgroup) {
  533: 	        foreach my $stu_group (@stu_groups) {
  534: 	            if ($stu_group eq $grp) {
  535: 	                $exclude = 0;
  536:     	            } 
  537: 	        }
  538:     	        if (($grp eq 'none') && !$group) {
  539:         	        $exclude = 0;
  540:         	}
  541: 	    }
  542: 	    if ($exclude) {
  543: 	        delete($classlist->{$student});
  544: 	    }
  545: 	}
  546: 	$section = ($section ne '' ? $section : 'none');
  547: 	if (&canview($section)) {
  548: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  549: 		$sections{$section}++;
  550: 		if ($classlist->{$student}) {
  551: 		    $fullnames{$student}=$fullname;
  552: 		}
  553: 	    } else {
  554: 		delete($classlist->{$student});
  555: 	    }
  556: 	} else {
  557: 	    delete($classlist->{$student});
  558: 	}
  559:     }
  560:     my %seen = ();
  561:     my @sections = sort(keys(%sections));
  562:     return ($classlist,\@sections,\%fullnames);
  563: }
  564: 
  565: sub canmodify {
  566:     my ($sec)=@_;
  567:     if ($perm{'mgr'}) {
  568: 	if (!defined($perm{'mgr_section'})) {
  569: 	    # can modify whole class
  570: 	    return 1;
  571: 	} else {
  572: 	    if ($sec eq $perm{'mgr_section'}) {
  573: 		#can modify the requested section
  574: 		return 1;
  575: 	    } else {
  576: 		# can't modify the request section
  577: 		return 0;
  578: 	    }
  579: 	}
  580:     }
  581:     #can't modify
  582:     return 0;
  583: }
  584: 
  585: sub canview {
  586:     my ($sec)=@_;
  587:     if ($perm{'vgr'}) {
  588: 	if (!defined($perm{'vgr_section'})) {
  589: 	    # can modify whole class
  590: 	    return 1;
  591: 	} else {
  592: 	    if ($sec eq $perm{'vgr_section'}) {
  593: 		#can modify the requested section
  594: 		return 1;
  595: 	    } else {
  596: 		# can't modify the request section
  597: 		return 0;
  598: 	    }
  599: 	}
  600:     }
  601:     #can't modify
  602:     return 0;
  603: }
  604: 
  605: #--- Retrieve the grade status of a student for all the parts
  606: sub student_gradeStatus {
  607:     my ($symb,$udom,$uname,$partlist) = @_;
  608:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  609:     my %partstatus = ();
  610:     foreach (@$partlist) {
  611: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  612: 	$status              = 'nothing' if ($status eq '');
  613: 	$partstatus{$_}      = $status;
  614: 	my $subkey           = "resource.$_.submitted_by";
  615: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  616:     }
  617:     return %partstatus;
  618: }
  619: 
  620: # hidden form and javascript that calls the form
  621: # Use by verifyscript and viewgrades
  622: # Shows a student's view of problem and submission
  623: sub jscriptNform {
  624:     my ($symb) = @_;
  625:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  626:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  627: 	'    function viewOneStudent(user,domain) {'."\n".
  628: 	'	document.onestudent.student.value = user;'."\n".
  629: 	'	document.onestudent.userdom.value = domain;'."\n".
  630: 	'	document.onestudent.submit();'."\n".
  631: 	'    }'."\n".
  632: 	'</script>'."\n";
  633:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  634: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  635: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  636: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  637: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  638: 	'<input type="hidden" name="command" value="submission" />'."\n".
  639: 	'<input type="hidden" name="student" value="" />'."\n".
  640: 	'<input type="hidden" name="userdom" value="" />'."\n".
  641: 	'</form>'."\n";
  642:     return $jscript;
  643: }
  644: 
  645: 
  646: 
  647: # Given the score (as a number [0-1] and the weight) what is the final
  648: # point value? This function will round to the nearest tenth, third,
  649: # or quarter if one of those is within the tolerance of .00001.
  650: sub compute_points {
  651:     my ($score, $weight) = @_;
  652:     
  653:     my $tolerance = .00001;
  654:     my $points = $score * $weight;
  655: 
  656:     # Check for nearness to 1/x.
  657:     my $check_for_nearness = sub {
  658:         my ($factor) = @_;
  659:         my $num = ($points * $factor) + $tolerance;
  660:         my $floored_num = floor($num);
  661:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  662:             return $floored_num / $factor;
  663:         }
  664:         return $points;
  665:     };
  666: 
  667:     $points = $check_for_nearness->(10);
  668:     $points = $check_for_nearness->(3);
  669:     $points = $check_for_nearness->(4);
  670:     
  671:     return $points;
  672: }
  673: 
  674: #------------------ End of general use routines --------------------
  675: 
  676: #
  677: # Find most similar essay
  678: #
  679: 
  680: sub most_similar {
  681:     my ($uname,$udom,$uessay,$old_essays)=@_;
  682: 
  683: # ignore spaces and punctuation
  684: 
  685:     $uessay=~s/\W+/ /gs;
  686: 
  687: # ignore empty submissions (occuring when only files are sent)
  688: 
  689:     unless ($uessay=~/\w+/) { return ''; }
  690: 
  691: # these will be returned. Do not care if not at least 50 percent similar
  692:     my $limit=0.6;
  693:     my $sname='';
  694:     my $sdom='';
  695:     my $scrsid='';
  696:     my $sessay='';
  697: # go through all essays ...
  698:     foreach my $tkey (keys(%$old_essays)) {
  699: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  700: # ... except the same student
  701:         next if (($tname eq $uname) && ($tdom eq $udom));
  702: 	my $tessay=$old_essays->{$tkey};
  703: 	$tessay=~s/\W+/ /gs;
  704: # String similarity gives up if not even limit
  705: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  706: # Found one
  707: 	if ($tsimilar>$limit) {
  708: 	    $limit=$tsimilar;
  709: 	    $sname=$tname;
  710: 	    $sdom=$tdom;
  711: 	    $scrsid=$tcrsid;
  712: 	    $sessay=$old_essays->{$tkey};
  713: 	}
  714:     }
  715:     if ($limit>0.6) {
  716:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  717:     } else {
  718:        return ('','','','',0);
  719:     }
  720: }
  721: 
  722: #-------------------------------------------------------------------
  723: 
  724: #------------------------------------ Receipt Verification Routines
  725: #
  726: #--- Check whether a receipt number is valid.---
  727: sub verifyreceipt {
  728:     my $request  = shift;
  729: 
  730:     my $courseid = $env{'request.course.id'};
  731:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  732: 	$env{'form.receipt'};
  733:     $receipt     =~ s/[^\-\d]//g;
  734:     my ($symb)   = &get_symb($request);
  735: 
  736:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
  737: 	$receipt.'</h3></span>'."\n".
  738: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
  739: 
  740:     my ($string,$contents,$matches) = ('','',0);
  741:     my (undef,undef,$fullname) = &getclasslist('all','0');
  742:     
  743:     my $receiptparts=0;
  744:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  745: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  746:     my $parts=['0'];
  747:     if ($receiptparts) { ($parts)=&response_type($symb); }
  748:     foreach (sort 
  749: 	     {
  750: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  751: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  752: 		 }
  753: 		 return $a cmp $b;
  754: 	     } (keys(%$fullname))) {
  755: 	my ($uname,$udom)=split(/\:/);
  756: 	foreach my $part (@$parts) {
  757: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  758: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
  759: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  760: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  761: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  762: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  763: 		if ($receiptparts) {
  764: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  765: 		}
  766: 		$contents.='</tr>'."\n";
  767: 		
  768: 		$matches++;
  769: 	    }
  770: 	}
  771:     }
  772:     if ($matches == 0) {
  773: 	$string = $title.'No match found for the above receipt.';
  774:     } else {
  775: 	$string = &jscriptNform($symb).$title.
  776: 	    'The above receipt matches the following student'.
  777: 	    ($matches <= 1 ? '.' : 's.')."\n".
  778: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
  779: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
  780: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
  781: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
  782: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
  783: 	if ($receiptparts) {
  784: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
  785: 	}
  786: 	$string.='</tr>'."\n".$contents.
  787: 	    '</table></td></tr></table>'."\n";
  788:     }
  789:     return $string.&show_grading_menu_form($symb);
  790: }
  791: 
  792: #--- This is called by a number of programs.
  793: #--- Called from the Grading Menu - View/Grade an individual student
  794: #--- Also called directly when one clicks on the subm button 
  795: #    on the problem page.
  796: sub listStudents {
  797:     my ($request) = shift;
  798: 
  799:     my ($symb) = &get_symb($request);
  800:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  801:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  802:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  803:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
  804:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  805:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  806:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  807: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  808: 
  809:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
  810: 	' Submissions for a Student or a Group of Students</span></h3>';
  811: 
  812:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  813: 
  814:     $request->print(<<LISTJAVASCRIPT);
  815: <script type="text/javascript" language="javascript">
  816:     function checkSelect(checkBox) {
  817: 	var ctr=0;
  818: 	var sense="";
  819: 	if (checkBox.length > 1) {
  820: 	    for (var i=0; i<checkBox.length; i++) {
  821: 		if (checkBox[i].checked) {
  822: 		    ctr++;
  823: 		}
  824: 	    }
  825: 	    sense = "a student or group of students";
  826: 	} else {
  827: 	    if (checkBox.checked) {
  828: 		ctr = 1;
  829: 	    }
  830: 	    sense = "the student";
  831: 	}
  832: 	if (ctr == 0) {
  833: 	    alert("Please select "+sense+" before clicking on the Next button.");
  834: 	    return false;
  835: 	}
  836: 	document.gradesub.submit();
  837:     }
  838: 
  839:     function reLoadList(formname) {
  840: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  841: 	formname.command.value = 'submission';
  842: 	formname.submit();
  843:     }
  844: </script>
  845: LISTJAVASCRIPT
  846: 
  847:     &commonJSfunctions($request);
  848:     $request->print($result);
  849: 
  850:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  851:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  852:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  853: 	"\n".$table.
  854: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
  855: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
  856: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
  857: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
  858: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
  859: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
  860: 	'&nbsp;<b>Submissions: </b>'."\n";
  861:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  862: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
  863:     }
  864:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  865:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  866:     $env{'form.Status'} = $saveStatus;
  867:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
  868: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
  869: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
  870: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
  871:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
  872:         '<option value="1">Whole Points</option>'.
  873:         '<option value=".5">Half Points</option>'.
  874:         '<option value=".25">Quarter Points</option>'.
  875:         '<option value=".1">Tenths of a Point</option>'.
  876:         '</select>'.
  877:         &build_section_inputs().
  878: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  879: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  880: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  881: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  882: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  883: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  884: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  885: 
  886:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  887: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
  888:     } else {
  889: 	$gradeTable.='<b>Student Status:</b> '.
  890: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
  891:     }
  892: 
  893:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
  894: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
  895: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
  896: 
  897: # checkall buttons
  898:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  899:     $gradeTable.='<input type="button" '."\n".
  900: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  901: 	'value="Next->" /> <br />'."\n";
  902:     $gradeTable.=&check_buttons();
  903:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
  904:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
  905:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
  906: 	'<table border="0"><tr bgcolor="#e6ffff">';
  907:     my $loop = 0;
  908:     while ($loop < 2) {
  909: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
  910: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
  911: 	if ($env{'form.showgrading'} eq 'yes' 
  912: 	    && $submitonly ne 'queued'
  913: 	    && $submitonly ne 'all') {
  914: 	    foreach (sort(@$partlist)) {
  915: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
  916: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
  917: 		    ' Status&nbsp;</b></td>';
  918: 	    }
  919: 	} elsif ($submitonly eq 'queued') {
  920: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
  921: 	}
  922: 	$loop++;
  923: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  924:     }
  925:     $gradeTable.='</tr>'."\n";
  926: 
  927:     my $ctr = 0;
  928:     foreach my $student (sort 
  929: 			 {
  930: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  931: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  932: 			     }
  933: 			     return $a cmp $b;
  934: 			 }
  935: 			 (keys(%$fullname))) {
  936: 	my ($uname,$udom) = split(/:/,$student);
  937: 
  938: 	my %status = ();
  939: 
  940: 	if ($submitonly eq 'queued') {
  941: 	    my %queue_status = 
  942: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  943: 							$udom,$uname);
  944: 	    next if (!defined($queue_status{'gradingqueue'}));
  945: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  946: 	}
  947: 
  948: 	if ($env{'form.showgrading'} eq 'yes' 
  949: 	    && $submitonly ne 'queued'
  950: 	    && $submitonly ne 'all') {
  951: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  952: 	    my $submitted = 0;
  953: 	    my $graded = 0;
  954: 	    my $incorrect = 0;
  955: 	    foreach (keys(%status)) {
  956: 		$submitted = 1 if ($status{$_} ne 'nothing');
  957: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
  958: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
  959: 		
  960: 		my ($foo,$partid,$foo1) = split(/\./,$_);
  961: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  962: 		    $submitted = 0;
  963: 		    my ($part)=split(/\./,$partid);
  964: 		    $gradeTable.='<input type="hidden" name="'.
  965: 			$student.':'.$part.':submitted_by" value="'.
  966: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
  967: 		}
  968: 	    }
  969: 	    
  970: 	    next if (!$submitted && ($submitonly eq 'yes' ||
  971: 				     $submitonly eq 'incorrect' ||
  972: 				     $submitonly eq 'graded'));
  973: 	    next if (!$graded && ($submitonly eq 'graded'));
  974: 	    next if (!$incorrect && $submitonly eq 'incorrect');
  975: 	}
  976: 
  977: 	$ctr++;
  978: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  979:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
  980: 	if ( $perm{'vgr'} eq 'F' ) {
  981: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
  982: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
  983:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
  984:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
  985: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
  986: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
  987: 	       '&nbsp;'.$section.'/'.$group.'</td>'."\n";
  988: 
  989: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
  990: 		foreach (sort keys(%status)) {
  991: 		    next if (/^resource.*?submitted_by$/);
  992: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
  993: 		}
  994: 	    }
  995: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
  996: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
  997: 	}
  998:     }
  999:     if ($ctr%2 ==1) {
 1000: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
 1001: 	    if ($env{'form.showgrading'} eq 'yes' 
 1002: 		&& $submitonly ne 'queued'
 1003: 		&& $submitonly ne 'all') {
 1004: 		foreach (@$partlist) {
 1005: 		    $gradeTable.='<td>&nbsp;</td>';
 1006: 		}
 1007: 	    } elsif ($submitonly eq 'queued') {
 1008: 		$gradeTable.='<td>&nbsp;</td>';
 1009: 	    }
 1010: 	$gradeTable.='</tr>';
 1011:     }
 1012: 
 1013:     $gradeTable.='</table></td></tr></table>'."\n".
 1014: 	'<input type="button" '.
 1015: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
 1016: 	'value="Next->" /></form>'."\n";
 1017:     if ($ctr == 0) {
 1018: 	my $num_students=(scalar(keys(%$fullname)));
 1019: 	if ($num_students eq 0) {
 1020: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
 1021: 	} else {
 1022: 	    my $submissions='submissions';
 1023: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
 1024: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
 1025: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
 1026: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
 1027: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
 1028: 		' students checked for '.$submissions.')</span><br />';
 1029: 	}
 1030:     } elsif ($ctr == 1) {
 1031: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
 1032:     }
 1033:     $gradeTable.=&show_grading_menu_form($symb);
 1034:     $request->print($gradeTable);
 1035:     return '';
 1036: }
 1037: 
 1038: #---- Called from the listStudents routine
 1039: 
 1040: sub check_script {
 1041:     my ($form, $type)=@_;
 1042:     my $chkallscript='<script type="text/javascript">
 1043:     function checkall() {
 1044:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1045:             ele = document.forms.'.$form.'.elements[i];
 1046:             if (ele.name == "'.$type.'") {
 1047:             document.forms.'.$form.'.elements[i].checked=true;
 1048:                                        }
 1049:         }
 1050:     }
 1051: 
 1052:     function checksec() {
 1053:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1054:             ele = document.forms.'.$form.'.elements[i];
 1055:            string = document.forms.'.$form.'.chksec.value;
 1056:            if
 1057:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1058:               document.forms.'.$form.'.elements[i].checked=true;
 1059:             }
 1060:         }
 1061:     }
 1062: 
 1063: 
 1064:     function uncheckall() {
 1065:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1066:             ele = document.forms.'.$form.'.elements[i];
 1067:             if (ele.name == "'.$type.'") {
 1068:             document.forms.'.$form.'.elements[i].checked=false;
 1069:                                        }
 1070:         }
 1071:     }
 1072: 
 1073: </script>'."\n";
 1074:     return $chkallscript;
 1075: }
 1076: 
 1077: sub check_buttons {
 1078:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
 1079:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
 1080:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
 1081:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1082:     return $buttons;
 1083: }
 1084: 
 1085: #     Displays the submissions for one student or a group of students
 1086: sub processGroup {
 1087:     my ($request)  = shift;
 1088:     my $ctr        = 0;
 1089:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1090:     my $total      = scalar(@stuchecked)-1;
 1091: 
 1092:     foreach my $student (@stuchecked) {
 1093: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1094: 	$env{'form.student'}        = $uname;
 1095: 	$env{'form.userdom'}        = $udom;
 1096: 	$env{'form.fullname'}       = $fullname;
 1097: 	&submission($request,$ctr,$total);
 1098: 	$ctr++;
 1099:     }
 1100:     return '';
 1101: }
 1102: 
 1103: #------------------------------------------------------------------------------------
 1104: #
 1105: #-------------------------- Next few routines handles grading by student, essentially
 1106: #                           handles essay response type problem/part
 1107: #
 1108: #--- Javascript to handle the submission page functionality ---
 1109: sub sub_page_js {
 1110:     my $request = shift;
 1111:     $request->print(<<SUBJAVASCRIPT);
 1112: <script type="text/javascript" language="javascript">
 1113:     function updateRadio(formname,id,weight) {
 1114: 	var gradeBox = formname["GD_BOX"+id];
 1115: 	var radioButton = formname["RADVAL"+id];
 1116: 	var oldpts = formname["oldpts"+id].value;
 1117: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1118: 	gradeBox.value = pts;
 1119: 	var resetbox = false;
 1120: 	if (isNaN(pts) || pts < 0) {
 1121: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
 1122: 	    for (var i=0; i<radioButton.length; i++) {
 1123: 		if (radioButton[i].checked) {
 1124: 		    gradeBox.value = i;
 1125: 		    resetbox = true;
 1126: 		}
 1127: 	    }
 1128: 	    if (!resetbox) {
 1129: 		formtextbox.value = "";
 1130: 	    }
 1131: 	    return;
 1132: 	}
 1133: 
 1134: 	if (pts > weight) {
 1135: 	    var resp = confirm("You entered a value ("+pts+
 1136: 			       ") greater than the weight for the part. Accept?");
 1137: 	    if (resp == false) {
 1138: 		gradeBox.value = oldpts;
 1139: 		return;
 1140: 	    }
 1141: 	}
 1142: 
 1143: 	for (var i=0; i<radioButton.length; i++) {
 1144: 	    radioButton[i].checked=false;
 1145: 	    if (pts == i && pts != "") {
 1146: 		radioButton[i].checked=true;
 1147: 	    }
 1148: 	}
 1149: 	updateSelect(formname,id);
 1150: 	formname["stores"+id].value = "0";
 1151:     }
 1152: 
 1153:     function writeBox(formname,id,pts) {
 1154: 	var gradeBox = formname["GD_BOX"+id];
 1155: 	if (checkSolved(formname,id) == 'update') {
 1156: 	    gradeBox.value = pts;
 1157: 	} else {
 1158: 	    var oldpts = formname["oldpts"+id].value;
 1159: 	    gradeBox.value = oldpts;
 1160: 	    var radioButton = formname["RADVAL"+id];
 1161: 	    for (var i=0; i<radioButton.length; i++) {
 1162: 		radioButton[i].checked=false;
 1163: 		if (i == oldpts) {
 1164: 		    radioButton[i].checked=true;
 1165: 		}
 1166: 	    }
 1167: 	}
 1168: 	formname["stores"+id].value = "0";
 1169: 	updateSelect(formname,id);
 1170: 	return;
 1171:     }
 1172: 
 1173:     function clearRadBox(formname,id) {
 1174: 	if (checkSolved(formname,id) == 'noupdate') {
 1175: 	    updateSelect(formname,id);
 1176: 	    return;
 1177: 	}
 1178: 	gradeSelect = formname["GD_SEL"+id];
 1179: 	for (var i=0; i<gradeSelect.length; i++) {
 1180: 	    if (gradeSelect[i].selected) {
 1181: 		var selectx=i;
 1182: 	    }
 1183: 	}
 1184: 	var stores = formname["stores"+id];
 1185: 	if (selectx == stores.value) { return };
 1186: 	var gradeBox = formname["GD_BOX"+id];
 1187: 	gradeBox.value = "";
 1188: 	var radioButton = formname["RADVAL"+id];
 1189: 	for (var i=0; i<radioButton.length; i++) {
 1190: 	    radioButton[i].checked=false;
 1191: 	}
 1192: 	stores.value = selectx;
 1193:     }
 1194: 
 1195:     function checkSolved(formname,id) {
 1196: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1197: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1198: 	    if (!reply) {return "noupdate";}
 1199: 	    formname.overRideScore.value = 'yes';
 1200: 	}
 1201: 	return "update";
 1202:     }
 1203: 
 1204:     function updateSelect(formname,id) {
 1205: 	formname["GD_SEL"+id][0].selected = true;
 1206: 	return;
 1207:     }
 1208: 
 1209: //=========== Check that a point is assigned for all the parts  ============
 1210:     function checksubmit(formname,val,total,parttot) {
 1211: 	formname.gradeOpt.value = val;
 1212: 	if (val == "Save & Next") {
 1213: 	    for (i=0;i<=total;i++) {
 1214: 		for (j=0;j<parttot;j++) {
 1215: 		    var partid = formname["partid"+i+"_"+j].value;
 1216: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1217: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1218: 			if (points == "") {
 1219: 			    var name = formname["name"+i].value;
 1220: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1221: 			    var resp = confirm("You did not assign a score for "+studentID+
 1222: 					       ", part "+partid+". Continue?");
 1223: 			    if (resp == false) {
 1224: 				formname["GD_BOX"+i+"_"+partid].focus();
 1225: 				return false;
 1226: 			    }
 1227: 			}
 1228: 		    }
 1229: 		    
 1230: 		}
 1231: 	    }
 1232: 	    
 1233: 	}
 1234: 	if (val == "Grade Student") {
 1235: 	    formname.showgrading.value = "yes";
 1236: 	    if (formname.Status.value == "") {
 1237: 		formname.Status.value = "Active";
 1238: 	    }
 1239: 	    formname.studentNo.value = total;
 1240: 	}
 1241: 	formname.submit();
 1242:     }
 1243: 
 1244: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1245:     function checkSubmitPage(formname,total) {
 1246: 	noscore = new Array(100);
 1247: 	var ptr = 0;
 1248: 	for (i=1;i<total;i++) {
 1249: 	    var partid = formname["q_"+i].value;
 1250: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1251: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1252: 		var status = formname["solved"+i+"_"+partid].value;
 1253: 		if (points == "" && status != "correct_by_student") {
 1254: 		    noscore[ptr] = i;
 1255: 		    ptr++;
 1256: 		}
 1257: 	    }
 1258: 	}
 1259: 	if (ptr != 0) {
 1260: 	    var sense = ptr == 1 ? ": " : "s: ";
 1261: 	    var prolist = "";
 1262: 	    if (ptr == 1) {
 1263: 		prolist = noscore[0];
 1264: 	    } else {
 1265: 		var i = 0;
 1266: 		while (i < ptr-1) {
 1267: 		    prolist += noscore[i]+", ";
 1268: 		    i++;
 1269: 		}
 1270: 		prolist += "and "+noscore[i];
 1271: 	    }
 1272: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1273: 	    if (resp == false) {
 1274: 		return false;
 1275: 	    }
 1276: 	}
 1277: 
 1278: 	formname.submit();
 1279:     }
 1280: </script>
 1281: SUBJAVASCRIPT
 1282: }
 1283: 
 1284: #--- javascript for essay type problem --
 1285: sub sub_page_kw_js {
 1286:     my $request = shift;
 1287:     my $iconpath = $request->dir_config('lonIconsURL');
 1288:     &commonJSfunctions($request);
 1289: 
 1290:     my $inner_js_msg_central=<<INNERJS;
 1291:     <script text="text/javascript">
 1292:     function checkInput() {
 1293:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1294:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1295:       var usrctr = document.msgcenter.usrctr.value;
 1296:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1297:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1298: 
 1299:       var msgchk = "";
 1300:       if (document.msgcenter.subchk.checked) {
 1301:          msgchk = "msgsub,";
 1302:       }
 1303:       var includemsg = 0;
 1304:       for (var i=1; i<=nmsg; i++) {
 1305:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1306:           var frmmsg = document.msgcenter["msg"+i];
 1307:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1308:           var showflg = opener.document.SCORE["shownOnce"+i];
 1309:           showflg.value = "1";
 1310:           var chkbox = document.msgcenter["msgn"+i];
 1311:           if (chkbox.checked) {
 1312:              msgchk += "savemsg"+i+",";
 1313:              includemsg = 1;
 1314:           }
 1315:       }
 1316:       if (document.msgcenter.newmsgchk.checked) {
 1317:          msgchk += "newmsg"+usrctr;
 1318:          includemsg = 1;
 1319:       }
 1320:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1321:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1322:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1323:       includemsg.value = msgchk;
 1324: 
 1325:       self.close()
 1326: 
 1327:     }
 1328:     </script>
 1329: INNERJS
 1330: 
 1331:     my $inner_js_highlight_central=<<INNERJS;
 1332:  <script type="text/javascript">
 1333:     function updateChoice(flag) {
 1334:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1335:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1336:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1337:       opener.document.SCORE.refresh.value = "on";
 1338:       if (opener.document.SCORE.keywords.value!=""){
 1339:          opener.document.SCORE.submit();
 1340:       }
 1341:       self.close()
 1342:     }
 1343: </script>
 1344: INNERJS
 1345: 
 1346:     my $start_page_msg_central = 
 1347:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1348: 				       {'js_ready'  => 1,
 1349: 					'only_body' => 1,
 1350: 					'bgcolor'   =>'#FFFFFF',});
 1351:     my $end_page_msg_central = 
 1352: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1353: 
 1354: 
 1355:     my $start_page_highlight_central = 
 1356:         &Apache::loncommon::start_page('Highlight Central',
 1357: 				       $inner_js_highlight_central,
 1358: 				       {'js_ready'  => 1,
 1359: 					'only_body' => 1,
 1360: 					'bgcolor'   =>'#FFFFFF',});
 1361:     my $end_page_highlight_central = 
 1362: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1363: 
 1364:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1365:     $docopen=~s/^document\.//;
 1366:     $request->print(<<SUBJAVASCRIPT);
 1367: <script type="text/javascript" language="javascript">
 1368: 
 1369: //===================== Show list of keywords ====================
 1370:   function keywords(formname) {
 1371:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1372:     if (nret==null) return;
 1373:     formname.keywords.value = nret;
 1374: 
 1375:     if (formname.keywords.value != "") {
 1376: 	formname.refresh.value = "on";
 1377: 	formname.submit();
 1378:     }
 1379:     return;
 1380:   }
 1381: 
 1382: //===================== Script to view submitted by ==================
 1383:   function viewSubmitter(submitter) {
 1384:     document.SCORE.refresh.value = "on";
 1385:     document.SCORE.NCT.value = "1";
 1386:     document.SCORE.unamedom0.value = submitter;
 1387:     document.SCORE.submit();
 1388:     return;
 1389:   }
 1390: 
 1391: //===================== Script to add keyword(s) ==================
 1392:   function getSel() {
 1393:     if (document.getSelection) txt = document.getSelection();
 1394:     else if (document.selection) txt = document.selection.createRange().text;
 1395:     else return;
 1396:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1397:     if (cleantxt=="") {
 1398: 	alert("Please select a word or group of words from document and then click this link.");
 1399: 	return;
 1400:     }
 1401:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1402:     if (nret==null) return;
 1403:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1404:     if (document.SCORE.keywords.value != "") {
 1405: 	document.SCORE.refresh.value = "on";
 1406: 	document.SCORE.submit();
 1407:     }
 1408:     return;
 1409:   }
 1410: 
 1411: //====================== Script for composing message ==============
 1412:    // preload images
 1413:    img1 = new Image();
 1414:    img1.src = "$iconpath/mailbkgrd.gif";
 1415:    img2 = new Image();
 1416:    img2.src = "$iconpath/mailto.gif";
 1417: 
 1418:   function msgCenter(msgform,usrctr,fullname) {
 1419:     var Nmsg  = msgform.savemsgN.value;
 1420:     savedMsgHeader(Nmsg,usrctr,fullname);
 1421:     var subject = msgform.msgsub.value;
 1422:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1423:     re = /msgsub/;
 1424:     var shwsel = "";
 1425:     if (re.test(msgchk)) { shwsel = "checked" }
 1426:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1427:     displaySubject(checkEntities(subject),shwsel);
 1428:     for (var i=1; i<=Nmsg; i++) {
 1429: 	var testmsg = "savemsg"+i+",";
 1430: 	re = new RegExp(testmsg,"g");
 1431: 	shwsel = "";
 1432: 	if (re.test(msgchk)) { shwsel = "checked" }
 1433: 	var message = document.SCORE["savemsg"+i].value;
 1434: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1435: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1436: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1437:     }
 1438:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1439:     shwsel = "";
 1440:     re = /newmsg/;
 1441:     if (re.test(msgchk)) { shwsel = "checked" }
 1442:     newMsg(newmsg,shwsel);
 1443:     msgTail(); 
 1444:     return;
 1445:   }
 1446: 
 1447:   function checkEntities(strx) {
 1448:     if (strx.length == 0) return strx;
 1449:     var orgStr = ["&", "<", ">", '"']; 
 1450:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1451:     var counter = 0;
 1452:     while (counter < 4) {
 1453: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1454: 	counter++;
 1455:     }
 1456:     return strx;
 1457:   }
 1458: 
 1459:   function strReplace(strx, orgStr, newStr) {
 1460:     return strx.split(orgStr).join(newStr);
 1461:   }
 1462: 
 1463:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1464:     var height = 70*Nmsg+250;
 1465:     var scrollbar = "no";
 1466:     if (height > 600) {
 1467: 	height = 600;
 1468: 	scrollbar = "yes";
 1469:     }
 1470:     var xpos = (screen.width-600)/2;
 1471:     xpos = (xpos < 0) ? '0' : xpos;
 1472:     var ypos = (screen.height-height)/2-30;
 1473:     ypos = (ypos < 0) ? '0' : ypos;
 1474: 
 1475:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1476:     pWin.focus();
 1477:     pDoc = pWin.document;
 1478:     pDoc.$docopen;
 1479:     pDoc.write('$start_page_msg_central');
 1480: 
 1481:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1482:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1483:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
 1484: 
 1485:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1486:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1487:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
 1488: }
 1489:     function displaySubject(msg,shwsel) {
 1490:     pDoc = pWin.document;
 1491:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1492:     pDoc.write("<td>Subject</td>");
 1493:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
 1494:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
 1495: }
 1496: 
 1497:   function displaySavedMsg(ctr,msg,shwsel) {
 1498:     pDoc = pWin.document;
 1499:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1500:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
 1501:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
 1502:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
 1503: }
 1504: 
 1505:   function newMsg(newmsg,shwsel) {
 1506:     pDoc = pWin.document;
 1507:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1508:     pDoc.write("<td align=\\"center\\">New</td>");
 1509:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
 1510:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
 1511: }
 1512: 
 1513:   function msgTail() {
 1514:     pDoc = pWin.document;
 1515:     pDoc.write("</table>");
 1516:     pDoc.write("</td></tr></table>&nbsp;");
 1517:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1518:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1519:     pDoc.write("</form>");
 1520:     pDoc.write('$end_page_msg_central');
 1521:     pDoc.close();
 1522: }
 1523: 
 1524: //====================== Script for keyword highlight options ==============
 1525:   function kwhighlight() {
 1526:     var kwclr    = document.SCORE.kwclr.value;
 1527:     var kwsize   = document.SCORE.kwsize.value;
 1528:     var kwstyle  = document.SCORE.kwstyle.value;
 1529:     var redsel = "";
 1530:     var grnsel = "";
 1531:     var blusel = "";
 1532:     if (kwclr=="red")   {var redsel="checked"};
 1533:     if (kwclr=="green") {var grnsel="checked"};
 1534:     if (kwclr=="blue")  {var blusel="checked"};
 1535:     var sznsel = "";
 1536:     var sz1sel = "";
 1537:     var sz2sel = "";
 1538:     if (kwsize=="0")  {var sznsel="checked"};
 1539:     if (kwsize=="+1") {var sz1sel="checked"};
 1540:     if (kwsize=="+2") {var sz2sel="checked"};
 1541:     var synsel = "";
 1542:     var syisel = "";
 1543:     var sybsel = "";
 1544:     if (kwstyle=="")    {var synsel="checked"};
 1545:     if (kwstyle=="<i>") {var syisel="checked"};
 1546:     if (kwstyle=="<b>") {var sybsel="checked"};
 1547:     highlightCentral();
 1548:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1549:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1550:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1551:     highlightend();
 1552:     return;
 1553:   }
 1554: 
 1555:   function highlightCentral() {
 1556: //    if (window.hwdWin) window.hwdWin.close();
 1557:     var xpos = (screen.width-400)/2;
 1558:     xpos = (xpos < 0) ? '0' : xpos;
 1559:     var ypos = (screen.height-330)/2-30;
 1560:     ypos = (ypos < 0) ? '0' : ypos;
 1561: 
 1562:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1563:     hwdWin.focus();
 1564:     var hDoc = hwdWin.document;
 1565:     hDoc.$docopen;
 1566:     hDoc.write('$start_page_highlight_central');
 1567:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1568:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
 1569: 
 1570:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1571:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1572:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
 1573:   }
 1574: 
 1575:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1576:     var hDoc = hwdWin.document;
 1577:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1578:     hDoc.write("<td align=\\"left\\">");
 1579:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
 1580:     hDoc.write("<td align=\\"left\\">");
 1581:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
 1582:     hDoc.write("<td align=\\"left\\">");
 1583:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
 1584:     hDoc.write("</tr>");
 1585:   }
 1586: 
 1587:   function highlightend() { 
 1588:     var hDoc = hwdWin.document;
 1589:     hDoc.write("</table>");
 1590:     hDoc.write("</td></tr></table>&nbsp;");
 1591:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1592:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1593:     hDoc.write("</form>");
 1594:     hDoc.write('$end_page_highlight_central');
 1595:     hDoc.close();
 1596:   }
 1597: 
 1598: </script>
 1599: SUBJAVASCRIPT
 1600: }
 1601: 
 1602: sub get_increment {
 1603:     my $increment = $env{'form.increment'};
 1604:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1605:         $increment != .1) {
 1606:         $increment = 1;
 1607:     }
 1608:     return $increment;
 1609: }
 1610: 
 1611: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1612: sub gradeBox {
 1613:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1614:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1615: 	'" src="'.$request->dir_config('lonIconsURL').
 1616: 	'/check.gif" height="16" border="0" />';
 1617:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1618:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
 1619: 		  '<span class="LC_info">problem weight assigned by computer</span>');
 1620:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1621:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1622: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1623:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1624:     my $display_part=&get_display_part($partid,$symb);
 1625:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1626: 				       [$partid]);
 1627:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1628:     if ($last_resets{$partid}) {
 1629:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1630:     }
 1631:     $result.='<table border="0"><tr><td>'.
 1632: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
 1633:     my $ctr = 0;
 1634:     my $thisweight = 0;
 1635:     my $increment = &get_increment();
 1636:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1637:     while ($thisweight<=$wgt) {
 1638: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1639: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1640: 	    $thisweight.')" value="'.$thisweight.'" '.
 1641: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1642: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1643:         $thisweight += $increment;
 1644: 	$ctr++;
 1645:     }
 1646:     $result.='</tr></table>';
 1647:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
 1648:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1649: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1650: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1651: 	$wgt.')" /></td>'."\n";
 1652:     $result.='<td>/'.$wgt.' '.$wgtmsg.
 1653: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1654: 	' </td><td>'."\n";
 1655:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1656: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1657:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1658: 	$result.='<option></option>'.
 1659: 	    '<option selected="selected">excused</option>';
 1660:     } else {
 1661: 	$result.='<option selected="selected"></option>'.
 1662: 	    '<option>excused</option>';
 1663:     }
 1664:     $result.='<option>reset status</option></select>'."\n";
 1665:     $result.="&nbsp;&nbsp;\n";
 1666:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1667: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1668: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1669: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1670:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1671:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1672:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1673:         $aggtries.'" />'."\n";
 1674:     $result.='</td></tr></table>'."\n";
 1675:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1676:     return $result;
 1677: }
 1678: 
 1679: sub handback_box {
 1680:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1681:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1682:     my (@respids);
 1683:      my @part_response_id = &flatten_responseType($responseType);
 1684:     foreach my $part_response_id (@part_response_id) {
 1685:     	my ($part,$resp) = @{ $part_response_id };
 1686:         if ($part eq $partid) {
 1687:             push(@respids,$resp);
 1688:         }
 1689:     }
 1690:     my $result;
 1691:     foreach my $respid (@respids) {
 1692: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1693: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1694: 	next if (!@$files);
 1695: 	my $file_counter = 1;
 1696: 	foreach my $file (@$files) {
 1697: 	    if ($file =~ /\/portfolio\//) {
 1698:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1699:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1700:     	        $file_disp = "$name.$ext";
 1701:     	        $file = $file_path.$file_disp;
 1702:     	        $result.=&mt('Return commented version of [_1] to student.',
 1703:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1704:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1705:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1706:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
 1707:     	        $file_counter++;
 1708: 	    }
 1709: 	}
 1710:     }
 1711:     return $result;    
 1712: }
 1713: 
 1714: sub show_problem {
 1715:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1716:     my $rendered;
 1717:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1718:     &Apache::lonxml::remember_problem_counter();
 1719:     if ($mode eq 'both' or $mode eq 'text') {
 1720: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1721: 						       $env{'request.course.id'},
 1722: 						       undef,\%form);
 1723:     }
 1724:     if ($removeform) {
 1725: 	$rendered=~s|<form(.*?)>||g;
 1726: 	$rendered=~s|</form>||g;
 1727: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1728:     }
 1729:     my $companswer;
 1730:     if ($mode eq 'both' or $mode eq 'answer') {
 1731: 	&Apache::lonxml::restore_problem_counter();
 1732: 	$companswer=
 1733: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1734: 						    $env{'request.course.id'},
 1735: 						    %form);
 1736:     }
 1737:     if ($removeform) {
 1738: 	$companswer=~s|<form(.*?)>||g;
 1739: 	$companswer=~s|</form>||g;
 1740: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1741:     }
 1742:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
 1743:     $result.='<table border="0" width="100%">';
 1744:     if ($viewon) {
 1745: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
 1746: 	if ($mode eq 'both' or $mode eq 'text') {
 1747: 	    $result.='View of the problem - ';
 1748: 	} else {
 1749: 	    $result.='Correct answer: ';
 1750: 	}
 1751: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
 1752:     }
 1753:     if ($mode eq 'both') {
 1754: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
 1755: 	$result.='<b>Correct answer:</b><br />'.$companswer;
 1756:     } elsif ($mode eq 'text') {
 1757: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
 1758:     } elsif ($mode eq 'answer') {
 1759: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
 1760:     }
 1761:     $result.='</td></tr></table>';
 1762:     $result.='</td></tr></table><br />';
 1763:     return $result;
 1764: }
 1765: 
 1766: sub files_exist {
 1767:     my ($r, $symb) = @_;
 1768:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1769: 
 1770:     foreach my $student (@students) {
 1771:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1772:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1773: 					      $udom,$uname);
 1774:         my ($string,$timestamp)= &get_last_submission(\%record);
 1775:         foreach my $submission (@$string) {
 1776:             my ($partid,$respid) =
 1777: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1778:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1779: 					   \%record);
 1780:             return 1 if (@$files);
 1781:         }
 1782:     }
 1783:     return 0;
 1784: }
 1785: 
 1786: sub download_all_link {
 1787:     my ($r,$symb) = @_;
 1788:     my $all_students = 
 1789: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1790: 
 1791:     my $parts =
 1792: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1793: 
 1794:     my $identifier = &Apache::loncommon::get_cgi_id();
 1795:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
 1796:                             'cgi.'.$identifier.'.symb' => $symb,
 1797:                             'cgi.'.$identifier.'.parts' => $parts,);
 1798:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1799: 	      &mt('Download All Submitted Documents').'</a>');
 1800:     return
 1801: }
 1802: 
 1803: sub build_section_inputs {
 1804:     my $section_inputs;
 1805:     if ($env{'form.section'} eq '') {
 1806:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1807:     } else {
 1808:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1809:         foreach my $section (@sections) {
 1810:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1811:         }
 1812:     }
 1813:     return $section_inputs;
 1814: }
 1815: 
 1816: # --------------------------- show submissions of a student, option to grade 
 1817: sub submission {
 1818:     my ($request,$counter,$total) = @_;
 1819:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1820:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1821:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1822:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1823:     my $symb = &get_symb($request); 
 1824:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1825: 
 1826:     if (!&canview($usec)) {
 1827: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1828: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1829: 			$env{'request.course.id'}.')</span>');
 1830: 	$request->print(&show_grading_menu_form($symb));
 1831: 	return;
 1832:     }
 1833: 
 1834:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1835:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1836:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1837:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1838:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1839: 	'" src="'.$request->dir_config('lonIconsURL').
 1840: 	'/check.gif" height="16" border="0" />';
 1841: 
 1842:     my %old_essays;
 1843:     # header info
 1844:     if ($counter == 0) {
 1845: 	&sub_page_js($request);
 1846: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1847: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1848: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1849: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1850: 	    &download_all_link($request, $symb);
 1851: 	}
 1852: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
 1853: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
 1854: 
 1855: 	if ($env{'form.handgrade'} eq 'no') {
 1856: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
 1857: 		$checkIcon.' symbol.'."\n";
 1858: 	    $request->print($checkMark);
 1859: 	}
 1860: 
 1861: 	# option to display problem, only once else it cause problems 
 1862:         # with the form later since the problem has a form.
 1863: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1864: 	    my $mode;
 1865: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1866: 		$mode='both';
 1867: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1868: 		$mode='text';
 1869: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1870: 		$mode='answer';
 1871: 	    }
 1872: 	    &Apache::lonxml::clear_problem_counter();
 1873: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1874: 	}
 1875: 
 1876: 	# kwclr is the only variable that is guaranteed to be non blank 
 1877:         # if this subroutine has been called once.
 1878: 	my %keyhash = ();
 1879: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1880: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1881: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1882: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1883: 
 1884: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1885: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1886: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1887: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1888: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1889: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1890: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1891: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1892: 	}
 1893: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1894: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1895: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1896: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1897: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1898: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1899: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1900: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1901: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1902: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1903: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1904: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1905: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1906: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1907: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1908: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1909: 			&build_section_inputs().
 1910: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1911: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1912: 			'<input type="hidden" name="NCT"'.
 1913: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1914: 	if ($env{'form.handgrade'} eq 'yes') {
 1915: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1916: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1917: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1918: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1919: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1920: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1921: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1922: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1923: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1924: 	    }
 1925: 	}
 1926: 	
 1927: 	my ($cts,$prnmsg) = (1,'');
 1928: 	while ($cts <= $env{'form.savemsgN'}) {
 1929: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1930: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1931: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1932: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1933: 		'" />'."\n".
 1934: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1935: 	    $cts++;
 1936: 	}
 1937: 	$request->print($prnmsg);
 1938: 
 1939: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 1940: #
 1941: # Print out the keyword options line
 1942: #
 1943: 	    $request->print(<<KEYWORDS);
 1944: &nbsp;<b>Keyword Options:</b>&nbsp;
 1945: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 1946: <a href="#" onMouseDown="javascript:getSel(); return false"
 1947:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 1948: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 1949: KEYWORDS
 1950: #
 1951: # Load the other essays for similarity check
 1952: #
 1953:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 1954: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 1955: 	    $apath=&escape($apath);
 1956: 	    $apath=~s/\W/\_/gs;
 1957: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 1958:         }
 1959:     }
 1960: 
 1961: # This is where output for one specific student would start
 1962:     my $bgcolor='#DDEEDD';
 1963:     if (int($counter/2) eq $counter) { $bgcolor='#DDDDEE'; }
 1964:     $request->print("\n\n".
 1965:                     '<p><table border="2"><tr><th bgcolor="'.$bgcolor.'">'.$env{'form.fullname'}.'</th></tr><tr><td bgcolor="'.$bgcolor.'">');
 1966: 
 1967:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 1968: 	my $mode;
 1969: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 1970: 	    $mode='both';
 1971: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 1972: 	    $mode='text';
 1973: 	} elsif ($env{'form.vAns'} eq 'all') {
 1974: 	    $mode='answer';
 1975: 	}
 1976: 	&Apache::lonxml::clear_problem_counter();
 1977: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
 1978:     }
 1979: 
 1980:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 1981:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1982: 
 1983:     # Display student info
 1984:     $request->print(($counter == 0 ? '' : '<br />'));
 1985:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
 1986: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
 1987: 
 1988:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
 1989:     $result.='<input type="hidden" name="name'.$counter.
 1990: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 1991: 
 1992:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 1993:     my @col_fullnames;
 1994:     my ($classlist,$fullname);
 1995:     if ($env{'form.handgrade'} eq 'yes') {
 1996: 	($classlist,undef,$fullname) = &getclasslist('all','0');
 1997: 	for (keys (%$handgrade)) {
 1998: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
 1999: 					    '.maxcollaborators',
 2000:                                             $symb,$udom,$uname);
 2001: 	    next if ($ncol <= 0);
 2002:             s/\_/\./g;
 2003:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
 2004:             my @goodcollaborators = ();
 2005:             my @badcollaborators  = ();
 2006: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
 2007: 		$_ =~ s/[\$\^\(\)]//g;
 2008: 		next if ($_ eq '');
 2009: 		my ($co_name,$co_dom) = split /\@|:/,$_;
 2010: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 2011: 		next if ($co_name eq $uname && $co_dom eq $udom);
 2012: 		# Doing this grep allows 'fuzzy' specification
 2013: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
 2014: 		if (! scalar(@Matches)) {
 2015: 		    push @badcollaborators,$_;
 2016: 		} else {
 2017: 		    push @goodcollaborators, @Matches;
 2018: 		}
 2019: 	    }
 2020:             if (scalar(@goodcollaborators) != 0) {
 2021:                 $result.='<b>Collaborators: </b>';
 2022:                 foreach (@goodcollaborators) {
 2023: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
 2024: 		    push @col_fullnames, $givenn.' '.$lastname;
 2025: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
 2026: 		}
 2027:                 $result.='<br />'."\n";
 2028: 		my ($part)=split(/\./,$_);
 2029: 		$result.='<input type="hidden" name="collaborator'.$counter.
 2030: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
 2031: 		    "\n";
 2032: 	    }
 2033: 	    if (scalar(@badcollaborators) > 0) {
 2034: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
 2035: 		$result.='This student has submitted ';
 2036: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
 2037: 		$result .= ': '.join(', ',@badcollaborators);
 2038: 		$result .= '</td></tr></table>';
 2039: 	    }         
 2040: 	    if (scalar(@badcollaborators > $ncol)) {
 2041: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
 2042: 		$result .= 'This student has submitted too many '.
 2043: 		    'collaborators.  Maximum is '.$ncol.'.';
 2044: 		$result .= '</td></tr></table>';
 2045: 	    }
 2046: 	}
 2047:     }
 2048:     $request->print($result."\n");
 2049: 
 2050:     # print student answer/submission
 2051:     # Options are (1) Handgaded submission only
 2052:     #             (2) Last submission, includes submission that is not handgraded 
 2053:     #                  (for multi-response type part)
 2054:     #             (3) Last submission plus the parts info
 2055:     #             (4) The whole record for this student
 2056:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2057: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2058: 	my $lastsubonly=''.
 2059: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
 2060: 	     $$timestamp)."</td></tr>\n";
 2061: 	if ($$timestamp eq '') {
 2062: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
 2063: 	} else {
 2064: 	    my %seenparts;
 2065: 	    my @part_response_id = &flatten_responseType($responseType);
 2066: 	    foreach my $part (@part_response_id) {
 2067: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2068: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2069: 
 2070: 		my ($partid,$respid) = @{ $part };
 2071: 		my $display_part=&get_display_part($partid,$symb);
 2072: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2073: 		    if (exists($seenparts{$partid})) { next; }
 2074: 		    $seenparts{$partid}=1;
 2075: 		    my $submitby='<b>Part:</b> '.$display_part.
 2076: 			' <b>Collaborative submission by:</b> '.
 2077: 			'<a href="javascript:viewSubmitter(\''.
 2078: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2079: 			'\');" target="_self">'.
 2080: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2081: 		    $request->print($submitby);
 2082: 		    next;
 2083: 		}
 2084: 		my $responsetype = $responseType->{$partid}->{$respid};
 2085: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2086: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
 2087: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2088: 			' )</span>&nbsp; &nbsp;'.
 2089: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
 2090: 		    next;
 2091: 		}
 2092: 		foreach (@$string) {
 2093: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
 2094: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2095: 		    my ($ressub,$subval) = split(/:/,$_,2);
 2096: 		    # Similarity check
 2097: 		    my $similar='';
 2098: 		    if($env{'form.checkPlag'}){
 2099: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2100: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2101: 			if ($osim) {
 2102: 			    $osim=int($osim*100.0);
 2103: 			    my %old_course_desc = 
 2104: 				&Apache::lonnet::coursedescription($ocrsid,
 2105: 								   {'one_time' => 1});
 2106: 
 2107: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2108: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
 2109: 				    $osim,
 2110: 				    &Apache::loncommon::plainname($oname,$odom),
 2111: 				    $oname,$odom,
 2112: 				    $old_course_desc{'description'},
 2113: 				    $old_course_desc{'num'},
 2114: 				    $old_course_desc{'domain'}).
 2115: 				'</span></h3><blockquote><i>'.
 2116: 				&keywords_highlight($oessay).
 2117: 				'</i></blockquote><hr />';
 2118: 			}
 2119: 		    }
 2120: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2121: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2122: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2123: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2124: 			my $display_part=&get_display_part($partid,$symb);
 2125: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
 2126: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2127: 			    ' )</span>&nbsp; &nbsp;';
 2128: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2129: 			if (@$files) {
 2130: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
 2131: 			    my $file_counter = 0;
 2132: 			    foreach my $file (@$files) {
 2133: 			        $file_counter ++;
 2134: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2135: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
 2136: 			    }
 2137: 			    $lastsubonly.='<br />';
 2138: 			}
 2139: 			$lastsubonly.='<b>Submitted Answer: </b>'.
 2140: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2141: 					 $respid,\%record,$order);
 2142: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2143: 		    }
 2144: 		}
 2145: 	    }
 2146: 	}
 2147: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
 2148: 	$request->print($lastsubonly);
 2149:     } elsif ($env{'form.lastSub'} eq 'datesub') {
 2150: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2151: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2152:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2153: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2154: 								 $env{'request.course.id'},
 2155: 								 $last,'.submission',
 2156: 								 'Apache::grades::keywords_highlight'));
 2157:     }
 2158: 
 2159:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2160: 	.$udom.'" />'."\n");
 2161:     
 2162:     # return if view submission with no grading option
 2163:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2164: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2165: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2166: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2167: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
 2168: 	if (($env{'form.command'} eq 'submission') || 
 2169: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2170: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2171: 	}
 2172: 	$request->print($toGrade);
 2173: 	return;
 2174:     } else {
 2175: 	$request->print('</td></tr></table></td></tr></table>'."\n");
 2176:     }
 2177: 
 2178:     # essay grading message center
 2179:     if ($env{'form.handgrade'} eq 'yes') {
 2180: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2181: 	my $msgfor = $givenn.' '.$lastname;
 2182: 	if (scalar(@col_fullnames) > 0) {
 2183: 	    my $lastone = pop @col_fullnames;
 2184: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
 2185: 	}
 2186: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2187: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2188: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2189: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2190: 	    ',\''.$msgfor.'\');" target="_self">'.
 2191: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2192: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2193: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2194: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2195: 	    '<br />&nbsp;('.
 2196: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
 2197: 	$request->print($result);
 2198:     }
 2199:     if ($perm{'vgr'}) {
 2200: 	$request->print('<br />'.
 2201: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2202: 						   $uname,$udom,'check'));
 2203:     }
 2204:     if ($perm{'opa'}) {
 2205: 	$request->print('<br />'.
 2206: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2207: 					 $uname,$udom,$symb,'check'));
 2208:     }
 2209: 
 2210:     my %seen = ();
 2211:     my @partlist;
 2212:     my @gradePartRespid;
 2213:     my @part_response_id = &flatten_responseType($responseType);
 2214:     foreach my $part_response_id (@part_response_id) {
 2215:     	my ($partid,$respid) = @{ $part_response_id };
 2216: 	my $part_resp = join('_',@{ $part_response_id });
 2217: 	next if ($seen{$partid} > 0);
 2218: 	$seen{$partid}++;
 2219: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2220: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2221: 	push @partlist,$partid;
 2222: 	push @gradePartRespid,$partid.'.'.$respid;
 2223: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2224:     }
 2225:     $result='<input type="hidden" name="partlist'.$counter.
 2226: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2227:     $result.='<input type="hidden" name="gradePartRespid'.
 2228: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2229:     my $ctr = 0;
 2230:     while ($ctr < scalar(@partlist)) {
 2231: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2232: 	    $partlist[$ctr].'" />'."\n";
 2233: 	$ctr++;
 2234:     }
 2235:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
 2236: 
 2237: # Done with printing info for one student
 2238: 
 2239:     $request->print('</td></tr></table></p>');
 2240: 
 2241: 
 2242:     # print end of form
 2243:     if ($counter == $total) {
 2244: 	my $endform='<table border="0"><tr><td>'."\n";
 2245: 	$endform.='<input type="button" value="Save & Next" '.
 2246: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2247: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2248: 	my $ntstu ='<select name="NTSTU">'.
 2249: 	    '<option>1</option><option>2</option>'.
 2250: 	    '<option>3</option><option>5</option>'.
 2251: 	    '<option>7</option><option>10</option></select>'."\n";
 2252: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2253: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2254: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
 2255: 	$endform.='<input type="button" value="Previous" '.
 2256: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2257: 	    '<input type="button" value="Next" '.
 2258: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2259: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
 2260:         $endform.="<input type='hidden' value='".&get_increment().
 2261:             "' name='increment' />";
 2262: 	$endform.='</td><tr></table></form>';
 2263: 	$endform.=&show_grading_menu_form($symb);
 2264: 	$request->print($endform);
 2265:     }
 2266:     return '';
 2267: }
 2268: 
 2269: #--- Retrieve the last submission for all the parts
 2270: sub get_last_submission {
 2271:     my ($returnhash)=@_;
 2272:     my (@string,$timestamp);
 2273:     if ($$returnhash{'version'}) {
 2274: 	my %lasthash=();
 2275: 	my ($version);
 2276: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2277: 	    foreach my $key (sort(split(/\:/,
 2278: 					$$returnhash{$version.':keys'}))) {
 2279: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2280: 		$timestamp = 
 2281: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
 2282: 	    }
 2283: 	}
 2284: 	foreach my $key (keys(%lasthash)) {
 2285: 	    next if ($key !~ /\.submission$/);
 2286: 
 2287: 	    my ($partid,$foo) = split(/submission$/,$key);
 2288: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2289: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2290: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2291: 	}
 2292:     }
 2293:     if (!@string) {
 2294: 	$string[0] =
 2295: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
 2296:     }
 2297:     return (\@string,\$timestamp);
 2298: }
 2299: 
 2300: #--- High light keywords, with style choosen by user.
 2301: sub keywords_highlight {
 2302:     my $string    = shift;
 2303:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2304:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2305:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2306:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2307:     foreach my $keyword (@keylist) {
 2308: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2309:     }
 2310:     return $string;
 2311: }
 2312: 
 2313: #--- Called from submission routine
 2314: sub processHandGrade {
 2315:     my ($request) = shift;
 2316:     my $symb   = &get_symb($request);
 2317:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2318:     my $button = $env{'form.gradeOpt'};
 2319:     my $ngrade = $env{'form.NCT'};
 2320:     my $ntstu  = $env{'form.NTSTU'};
 2321:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2322:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2323: 
 2324:     if ($button eq 'Save & Next') {
 2325: 	my $ctr = 0;
 2326: 	while ($ctr < $ngrade) {
 2327: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2328: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2329: 	    if ($errorflag eq 'no_score') {
 2330: 		$ctr++;
 2331: 		next;
 2332: 	    }
 2333: 	    if ($errorflag eq 'not_allowed') {
 2334: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2335: 		$ctr++;
 2336: 		next;
 2337: 	    }
 2338: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2339: 	    my ($subject,$message,$msgstatus) = ('','','');
 2340: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2341:             my ($feedurl,$showsymb) =
 2342: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2343: 	    my $messagetail;
 2344: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2345: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2346: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2347: 		$subject.=' ['.$restitle.']';
 2348: 		my (@msgnum) = split(/,/,$includemsg);
 2349: 		foreach (@msgnum) {
 2350: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2351: 		}
 2352: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2353: 		if ($env{'form.withgrades'.$ctr}) {
 2354: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2355: 		    $messagetail = " for <a href=\"".
 2356: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2357: 		}
 2358: 		$msgstatus = 
 2359:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2360: 						     $message.$messagetail,
 2361:                                                      undef,$feedurl,undef,
 2362:                                                      undef,undef,$showsymb,
 2363:                                                      $restitle);
 2364: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
 2365: 				$msgstatus);
 2366: 	    }
 2367: 	    if ($env{'form.collaborator'.$ctr}) {
 2368: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2369: 		foreach my $collabstr (@collabstrs) {
 2370: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2371: 		    foreach my $collaborator (@collaborators) {
 2372: 			my ($errorflag,$pts,$wgt) = 
 2373: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2374: 					   $env{'form.unamedom'.$ctr},$part);
 2375: 			if ($errorflag eq 'not_allowed') {
 2376: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2377: 			    next;
 2378: 			} elsif ($message ne '') {
 2379: 			    my ($baseurl,$showsymb) = 
 2380: 				&get_feedurl_and_symb($symb,$collaborator,
 2381: 						      $udom);
 2382: 			    if ($env{'form.withgrades'.$ctr}) {
 2383: 				$messagetail = " for <a href=\"".
 2384:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2385: 			    }
 2386: 			    $msgstatus = 
 2387: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2388: 			}
 2389: 		    }
 2390: 		}
 2391: 	    }
 2392: 	    $ctr++;
 2393: 	}
 2394:     }
 2395: 
 2396:     if ($env{'form.handgrade'} eq 'yes') {
 2397: 	# Keywords sorted in alphabatical order
 2398: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2399: 	my %keyhash = ();
 2400: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2401: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2402: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2403: 	$env{'form.keywords'} = join(' ',@keywords);
 2404: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2405: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2406: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2407: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2408: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2409: 
 2410: 	# message center - Order of message gets changed. Blank line is eliminated.
 2411: 	# New messages are saved in env for the next student.
 2412: 	# All messages are saved in nohist_handgrade.db
 2413: 	my ($ctr,$idx) = (1,1);
 2414: 	while ($ctr <= $env{'form.savemsgN'}) {
 2415: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2416: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2417: 		$idx++;
 2418: 	    }
 2419: 	    $ctr++;
 2420: 	}
 2421: 	$ctr = 0;
 2422: 	while ($ctr < $ngrade) {
 2423: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2424: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2425: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2426: 		$idx++;
 2427: 	    }
 2428: 	    $ctr++;
 2429: 	}
 2430: 	$env{'form.savemsgN'} = --$idx;
 2431: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2432: 	my $putresult = &Apache::lonnet::put
 2433: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2434:     }
 2435:     # Called by Save & Refresh from Highlight Attribute Window
 2436:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2437:     if ($env{'form.refresh'} eq 'on') {
 2438: 	my ($ctr,$total) = (0,0);
 2439: 	while ($ctr < $ngrade) {
 2440: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2441: 	    $ctr++;
 2442: 	}
 2443: 	$env{'form.NTSTU'}=$ngrade;
 2444: 	$ctr = 0;
 2445: 	while ($ctr < $total) {
 2446: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2447: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2448: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2449: 	    &submission($request,$ctr,$total-1);
 2450: 	    $ctr++;
 2451: 	}
 2452: 	return '';
 2453:     }
 2454: 
 2455: # Go directly to grade student - from submission or link from chart page
 2456:     if ($button eq 'Grade Student') {
 2457: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2458: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2459: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2460: 	$env{'form.fullname'} = $$fullname{$processUser};
 2461: 	&submission($request,0,0);
 2462: 	return '';
 2463:     }
 2464: 
 2465:     # Get the next/previous one or group of students
 2466:     my $firststu = $env{'form.unamedom0'};
 2467:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2468:     my $ctr = 2;
 2469:     while ($laststu eq '') {
 2470: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2471: 	$ctr++;
 2472: 	$laststu = $firststu if ($ctr > $ngrade);
 2473:     }
 2474: 
 2475:     my (@parsedlist,@nextlist);
 2476:     my ($nextflg) = 0;
 2477:     foreach (sort 
 2478: 	     {
 2479: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2480: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2481: 		 }
 2482: 		 return $a cmp $b;
 2483: 	     } (keys(%$fullname))) {
 2484: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2485: 	    push @parsedlist,$_;
 2486: 	}
 2487: 	$nextflg = 1 if ($_ eq $laststu);
 2488: 	if ($button eq 'Previous') {
 2489: 	    last if ($_ eq $firststu);
 2490: 	    push @parsedlist,$_;
 2491: 	}
 2492:     }
 2493:     $ctr = 0;
 2494:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2495:     my ($partlist) = &response_type($symb);
 2496:     foreach my $student (@parsedlist) {
 2497: 	my $submitonly=$env{'form.submitonly'};
 2498: 	my ($uname,$udom) = split(/:/,$student);
 2499: 	
 2500: 	if ($submitonly eq 'queued') {
 2501: 	    my %queue_status = 
 2502: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2503: 							$udom,$uname);
 2504: 	    next if (!defined($queue_status{'gradingqueue'}));
 2505: 	}
 2506: 
 2507: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2508: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2509: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2510: 	    my $submitted = 0;
 2511: 	    my $ungraded = 0;
 2512: 	    my $incorrect = 0;
 2513: 	    foreach (keys(%status)) {
 2514: 		$submitted = 1 if ($status{$_} ne 'nothing');
 2515: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
 2516: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 2517: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 2518: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2519: 		    $submitted = 0;
 2520: 		}
 2521: 	    }
 2522: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2523: 				     $submitonly eq 'incorrect' ||
 2524: 				     $submitonly eq 'graded'));
 2525: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2526: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2527: 	}
 2528: 	push @nextlist,$student if ($ctr < $ntstu);
 2529: 	last if ($ctr == $ntstu);
 2530: 	$ctr++;
 2531:     }
 2532: 
 2533:     $ctr = 0;
 2534:     my $total = scalar(@nextlist)-1;
 2535: 
 2536:     foreach (sort @nextlist) {
 2537: 	my ($uname,$udom,$submitter) = split(/:/);
 2538: 	$env{'form.student'}  = $uname;
 2539: 	$env{'form.userdom'}  = $udom;
 2540: 	$env{'form.fullname'} = $$fullname{$_};
 2541: 	&submission($request,$ctr,$total);
 2542: 	$ctr++;
 2543:     }
 2544:     if ($total < 0) {
 2545: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
 2546: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
 2547: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
 2548: 	$the_end.=&show_grading_menu_form($symb);
 2549: 	$request->print($the_end);
 2550:     }
 2551:     return '';
 2552: }
 2553: 
 2554: #---- Save the score and award for each student, if changed
 2555: sub saveHandGrade {
 2556:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2557:     my @version_parts;
 2558:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2559: 					   $env{'request.course.id'});
 2560:     if (!&canmodify($usec)) { return('not_allowed'); }
 2561:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2562:     my @parts_graded;
 2563:     my %newrecord  = ();
 2564:     my ($pts,$wgt) = ('','');
 2565:     my %aggregate = ();
 2566:     my $aggregateflag = 0;
 2567:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2568:     foreach my $new_part (@parts) {
 2569: 	#collaborator ($submi may vary for different parts
 2570: 	if ($submitter && $new_part ne $part) { next; }
 2571: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2572: 	if ($dropMenu eq 'excused') {
 2573: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2574: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2575: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2576: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2577: 		}
 2578: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2579: 	    }
 2580: 	} elsif ($dropMenu eq 'reset status'
 2581: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2582: 	    foreach my $key (keys (%record)) {
 2583: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2584: 	    }
 2585: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2586: 		"$env{'user.name'}:$env{'user.domain'}";
 2587:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2588: 
 2589:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2590: 					       [$new_part]);
 2591:             my $aggtries =$totaltries;
 2592:             if ($last_resets{$new_part}) {
 2593:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2594: 					   $new_part);
 2595:             }
 2596: 
 2597:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2598:             if ($aggtries > 0) {
 2599:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2600:                 $aggregateflag = 1;
 2601:             }
 2602: 	} elsif ($dropMenu eq '') {
 2603: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2604: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2605: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2606: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2607: 		next;
 2608: 	    }
 2609: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2610: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2611: 	    my $partial= $pts/$wgt;
 2612: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2613: 		#do not update score for part if not changed.
 2614:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2615: 		next;
 2616: 	    } else {
 2617: 	        push @parts_graded, $new_part;
 2618: 	    }
 2619: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2620: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2621: 	    }
 2622: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2623: 	    if ($partial == 0) {
 2624: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2625: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2626: 		}
 2627: 	    } else {
 2628: 		if ($record{$reckey} ne 'correct_by_override') {
 2629: 		    $newrecord{$reckey} = 'correct_by_override';
 2630: 		}
 2631: 	    }	    
 2632: 	    if ($submitter && 
 2633: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2634: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2635: 	    }
 2636: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2637: 		"$env{'user.name'}:$env{'user.domain'}";
 2638: 	}
 2639: 	# unless problem has been graded, set flag to version the submitted files
 2640: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2641: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2642: 	        $dropMenu eq 'reset status')
 2643: 	   {
 2644: 	    push (@version_parts,$new_part);
 2645: 	}
 2646:     }
 2647:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2648:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2649: 
 2650:     if (%newrecord) {
 2651:         if (@version_parts) {
 2652:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2653:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2654: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2655: 	    foreach my $new_part (@version_parts) {
 2656: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2657: 				$new_part,\%newrecord);
 2658: 	    }
 2659:         }
 2660: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2661: 				$env{'request.course.id'},$domain,$stuname);
 2662: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2663: 				     $cdom,$cnum,$domain,$stuname);
 2664:     }
 2665:     if ($aggregateflag) {
 2666:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2667: 			      $cdom,$cnum);
 2668:     }
 2669:     return ('',$pts,$wgt);
 2670: }
 2671: 
 2672: sub check_and_remove_from_queue {
 2673:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2674:     my @ungraded_parts;
 2675:     foreach my $part (@{$parts}) {
 2676: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2677: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2678: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2679: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2680: 		) {
 2681: 	    push(@ungraded_parts, $part);
 2682: 	}
 2683:     }
 2684:     if ( !@ungraded_parts ) {
 2685: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2686: 					       $cnum,$domain,$stuname);
 2687:     }
 2688: }
 2689: 
 2690: sub handback_files {
 2691:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2692:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
 2693:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2694: 
 2695:     my @part_response_id = &flatten_responseType($responseType);
 2696:     foreach my $part_response_id (@part_response_id) {
 2697:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2698: 	my $part_resp = join('_',@{ $part_response_id });
 2699:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2700:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2701:                 my $file_counter = 1;
 2702: 		my $file_msg;
 2703:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2704:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2705:                     my ($directory,$answer_file) = 
 2706:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2707:                     my ($answer_name,$answer_ver,$answer_ext) =
 2708: 		        &file_name_version_ext($answer_file);
 2709: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2710: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
 2711: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2712:                     # fix file name
 2713:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2714:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2715:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2716:             	                                $save_file_name);
 2717:                     if ($result !~ m|^/uploaded/|) {
 2718:                         $request->print('<span class="LC_error">An error occurred ('.$result.
 2719:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
 2720:                     } else {
 2721:                         # mark the file as read only
 2722:                         my @files = ($save_file_name);
 2723:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2724:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2725: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2726: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2727: 			}
 2728:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2729: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2730: 
 2731:                     }
 2732:                     $request->print("<br />".$fname." will be the uploaded file name");
 2733:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2734:                     $file_counter++;
 2735:                 }
 2736: 		my $subject = "File Handed Back by Instructor ";
 2737: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2738: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2739: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2740: 		$message .= " and can be found in your portfolio space.";
 2741: 		my ($feedurl,$showsymb) = 
 2742: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2743:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2744: 		my $msgstatus = 
 2745:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2746: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2747:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2748:             }
 2749:         }
 2750:     return;
 2751: }
 2752: 
 2753: sub get_feedurl_and_symb {
 2754:     my ($symb,$uname,$udom) = @_;
 2755:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2756:     $url = &Apache::lonnet::clutter($url);
 2757:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2758: 					$symb,$udom,$uname);
 2759:     if ($encrypturl =~ /^yes$/i) {
 2760: 	&Apache::lonenc::encrypted(\$url,1);
 2761: 	&Apache::lonenc::encrypted(\$symb,1);
 2762:     }
 2763:     return ($url,$symb);
 2764: }
 2765: 
 2766: sub get_submitted_files {
 2767:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2768:     my @files;
 2769:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2770:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2771:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2772:     	    push(@files,$file_url.$file);
 2773:         }
 2774:     }
 2775:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2776:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2777:     }
 2778:     return (\@files);
 2779: }
 2780: 
 2781: # ----------- Provides number of tries since last reset.
 2782: sub get_num_tries {
 2783:     my ($record,$last_reset,$part) = @_;
 2784:     my $timestamp = '';
 2785:     my $num_tries = 0;
 2786:     if ($$record{'version'}) {
 2787:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2788:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2789:                 $timestamp = $$record{$version.':timestamp'};
 2790:                 if ($timestamp > $last_reset) {
 2791:                     $num_tries ++;
 2792:                 } else {
 2793:                     last;
 2794:                 }
 2795:             }
 2796:         }
 2797:     }
 2798:     return $num_tries;
 2799: }
 2800: 
 2801: # ----------- Determine decrements required in aggregate totals 
 2802: sub decrement_aggs {
 2803:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2804:     my %decrement = (
 2805:                         attempts => 0,
 2806:                         users => 0,
 2807:                         correct => 0
 2808:                     );
 2809:     $decrement{'attempts'} = $aggtries;
 2810:     if ($solvedstatus =~ /^correct/) {
 2811:         $decrement{'correct'} = 1;
 2812:     }
 2813:     if ($aggtries == $totaltries) {
 2814:         $decrement{'users'} = 1;
 2815:     }
 2816:     foreach my $type (keys (%decrement)) {
 2817:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2818:     }
 2819:     return;
 2820: }
 2821: 
 2822: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2823: sub get_last_resets {
 2824:     my ($symb,$courseid,$partids) =@_;
 2825:     my %last_resets;
 2826:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2827:     my $cname = $env{'course.'.$courseid.'.num'};
 2828:     my @keys;
 2829:     foreach my $part (@{$partids}) {
 2830: 	push(@keys,"$symb\0$part\0resettime");
 2831:     }
 2832:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2833: 				     $cdom,$cname);
 2834:     foreach my $part (@{$partids}) {
 2835: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2836:     }
 2837:     return %last_resets;
 2838: }
 2839: 
 2840: # ----------- Handles creating versions for portfolio files as answers
 2841: sub version_portfiles {
 2842:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2843:     my $version_parts = join('|',@$v_flag);
 2844:     my @returned_keys;
 2845:     my $parts = join('|', @$parts_graded);
 2846:     my $portfolio_root = &propath($domain,$stu_name).
 2847: 	'/userfiles/portfolio';
 2848:     foreach my $key (keys(%$record)) {
 2849:         my $new_portfiles;
 2850:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2851:             my @versioned_portfiles;
 2852:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2853:             foreach my $file (@portfiles) {
 2854:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2855:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2856: 		my ($answer_name,$answer_ver,$answer_ext) =
 2857: 		    &file_name_version_ext($answer_file);
 2858:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
 2859:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2860:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2861:                 if ($new_answer ne 'problem getting file') {
 2862:                     push(@versioned_portfiles, $directory.$new_answer);
 2863:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2864:                         [$directory.$new_answer],
 2865:                         [$symb,$env{'request.course.id'},'graded']);
 2866:                 }
 2867:             }
 2868:             $$record{$key} = join(',',@versioned_portfiles);
 2869:             push(@returned_keys,$key);
 2870:         }
 2871:     } 
 2872:     return (@returned_keys);   
 2873: }
 2874: 
 2875: sub get_next_version {
 2876:     my ($answer_name, $answer_ext, $dir_list) = @_;
 2877:     my $version;
 2878:     foreach my $row (@$dir_list) {
 2879:         my ($file) = split(/\&/,$row,2);
 2880:         my ($file_name,$file_version,$file_ext) =
 2881: 	    &file_name_version_ext($file);
 2882:         if (($file_name eq $answer_name) && 
 2883: 	    ($file_ext eq $answer_ext)) {
 2884:                 # gets here if filename and extension match, regardless of version
 2885:                 if ($file_version ne '') {
 2886:                 # a versioned file is found  so save it for later
 2887:                 if ($file_version > $version) {
 2888: 		    $version = $file_version;
 2889: 	        }
 2890:             }
 2891:         }
 2892:     } 
 2893:     $version ++;
 2894:     return($version);
 2895: }
 2896: 
 2897: sub version_selected_portfile {
 2898:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 2899:     my ($answer_name,$answer_ver,$answer_ext) =
 2900:         &file_name_version_ext($file_name);
 2901:     my $new_answer;
 2902:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 2903:     if($env{'form.copy'} eq '-1') {
 2904:         $new_answer = 'problem getting file';
 2905:     } else {
 2906:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 2907:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 2908:                             $stu_name,$domain,'copy',
 2909: 		        '/portfolio'.$directory.$new_answer);
 2910:     }    
 2911:     return ($new_answer);
 2912: }
 2913: 
 2914: sub file_name_version_ext {
 2915:     my ($file)=@_;
 2916:     my @file_parts = split(/\./, $file);
 2917:     my ($name,$version,$ext);
 2918:     if (@file_parts > 1) {
 2919: 	$ext=pop(@file_parts);
 2920: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 2921: 	    $version=pop(@file_parts);
 2922: 	}
 2923: 	$name=join('.',@file_parts);
 2924:     } else {
 2925: 	$name=join('.',@file_parts);
 2926:     }
 2927:     return($name,$version,$ext);
 2928: }
 2929: 
 2930: #--------------------------------------------------------------------------------------
 2931: #
 2932: #-------------------------- Next few routines handles grading by section or whole class
 2933: #
 2934: #--- Javascript to handle grading by section or whole class
 2935: sub viewgrades_js {
 2936:     my ($request) = shift;
 2937: 
 2938:     $request->print(<<VIEWJAVASCRIPT);
 2939: <script type="text/javascript" language="javascript">
 2940:    function writePoint(partid,weight,point) {
 2941: 	var radioButton = document.classgrade["RADVAL_"+partid];
 2942: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 2943: 	if (point == "textval") {
 2944: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 2945: 	    if (isNaN(point) || parseFloat(point) < 0) {
 2946: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 2947: 		var resetbox = false;
 2948: 		for (var i=0; i<radioButton.length; i++) {
 2949: 		    if (radioButton[i].checked) {
 2950: 			textbox.value = i;
 2951: 			resetbox = true;
 2952: 		    }
 2953: 		}
 2954: 		if (!resetbox) {
 2955: 		    textbox.value = "";
 2956: 		}
 2957: 		return;
 2958: 	    }
 2959: 	    if (parseFloat(point) > parseFloat(weight)) {
 2960: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 2961: 				   ") greater than the weight for the part. Accept?");
 2962: 		if (resp == false) {
 2963: 		    textbox.value = "";
 2964: 		    return;
 2965: 		}
 2966: 	    }
 2967: 	    for (var i=0; i<radioButton.length; i++) {
 2968: 		radioButton[i].checked=false;
 2969: 		if (parseFloat(point) == i) {
 2970: 		    radioButton[i].checked=true;
 2971: 		}
 2972: 	    }
 2973: 
 2974: 	} else {
 2975: 	    textbox.value = parseFloat(point);
 2976: 	}
 2977: 	for (i=0;i<document.classgrade.total.value;i++) {
 2978: 	    var user = document.classgrade["ctr"+i].value;
 2979: 	    user = user.replace(new RegExp(':', 'g'),"_");
 2980: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 2981: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 2982: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 2983: 	    if (saveval != "correct") {
 2984: 		scorename.value = point;
 2985: 		if (selname[0].selected != true) {
 2986: 		    selname[0].selected = true;
 2987: 		}
 2988: 	    }
 2989: 	}
 2990: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 2991:     }
 2992: 
 2993:     function writeRadText(partid,weight) {
 2994: 	var selval   = document.classgrade["SELVAL_"+partid];
 2995: 	var radioButton = document.classgrade["RADVAL_"+partid];
 2996:         var override = document.classgrade["FORCE_"+partid].checked;
 2997: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 2998: 	if (selval[1].selected || selval[2].selected) {
 2999: 	    for (var i=0; i<radioButton.length; i++) {
 3000: 		radioButton[i].checked=false;
 3001: 
 3002: 	    }
 3003: 	    textbox.value = "";
 3004: 
 3005: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3006: 		var user = document.classgrade["ctr"+i].value;
 3007: 		user = user.replace(new RegExp(':', 'g'),"_");
 3008: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3009: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3010: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3011: 		if ((saveval != "correct") || override) {
 3012: 		    scorename.value = "";
 3013: 		    if (selval[1].selected) {
 3014: 			selname[1].selected = true;
 3015: 		    } else {
 3016: 			selname[2].selected = true;
 3017: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 3018: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 3019: 		    }
 3020: 		}
 3021: 	    }
 3022: 	} else {
 3023: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3024: 		var user = document.classgrade["ctr"+i].value;
 3025: 		user = user.replace(new RegExp(':', 'g'),"_");
 3026: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3027: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3028: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3029: 		if ((saveval != "correct") || override) {
 3030: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3031: 		    selname[0].selected = true;
 3032: 		}
 3033: 	    }
 3034: 	}	    
 3035:     }
 3036: 
 3037:     function changeSelect(partid,user) {
 3038: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3039: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3040: 	var point  = textbox.value;
 3041: 	var weight = document.classgrade["weight_"+partid].value;
 3042: 
 3043: 	if (isNaN(point) || parseFloat(point) < 0) {
 3044: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 3045: 	    textbox.value = "";
 3046: 	    return;
 3047: 	}
 3048: 	if (parseFloat(point) > parseFloat(weight)) {
 3049: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3050: 			       ") greater than the weight of the part. Accept?");
 3051: 	    if (resp == false) {
 3052: 		textbox.value = "";
 3053: 		return;
 3054: 	    }
 3055: 	}
 3056: 	selval[0].selected = true;
 3057:     }
 3058: 
 3059:     function changeOneScore(partid,user) {
 3060: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3061: 	if (selval[1].selected || selval[2].selected) {
 3062: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3063: 	    if (selval[2].selected) {
 3064: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3065: 	    }
 3066:         }
 3067:     }
 3068: 
 3069:     function resetEntry(numpart) {
 3070: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3071: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3072: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3073: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3074: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3075: 	    for (var i=0; i<radioButton.length; i++) {
 3076: 		radioButton[i].checked=false;
 3077: 
 3078: 	    }
 3079: 	    textbox.value = "";
 3080: 	    selval[0].selected = true;
 3081: 
 3082: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3083: 		var user = document.classgrade["ctr"+i].value;
 3084: 		user = user.replace(new RegExp(':', 'g'),"_");
 3085: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3086: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3087: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3088: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3089: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3090: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3091: 		if (saveselval == "excused") {
 3092: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3093: 		} else {
 3094: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3095: 		}
 3096: 	    }
 3097: 	}
 3098:     }
 3099: 
 3100: </script>
 3101: VIEWJAVASCRIPT
 3102: }
 3103: 
 3104: #--- show scores for a section or whole class w/ option to change/update a score
 3105: sub viewgrades {
 3106:     my ($request) = shift;
 3107:     &viewgrades_js($request);
 3108: 
 3109:     my ($symb) = &get_symb($request);
 3110:     #need to make sure we have the correct data for later EXT calls, 
 3111:     #thus invalidate the cache
 3112:     &Apache::lonnet::devalidatecourseresdata(
 3113:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3114:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3115:     &Apache::lonnet::clear_EXT_cache_status();
 3116: 
 3117:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3118:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
 3119: 
 3120:     #view individual student submission form - called using Javascript viewOneStudent
 3121:     $result.=&jscriptNform($symb);
 3122: 
 3123:     #beginning of class grading form
 3124:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3125:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3126: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3127: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3128: 	&build_section_inputs().
 3129: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3130: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3131: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3132: 
 3133:     my $sectionClass;
 3134:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3135:     if ($env{'form.section'} eq 'all') {
 3136: 	$sectionClass='Class </h3>';
 3137:     } elsif ($env{'form.section'} eq 'none') {
 3138: 	$sectionClass=&mt('Students in no Section').'</h3>';
 3139:     } else {
 3140: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
 3141:     }
 3142:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
 3143:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
 3144: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
 3145:     #radio buttons/text box for assigning points for a section or class.
 3146:     #handles different parts of a problem
 3147:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3148:     my %weight = ();
 3149:     my $ctsparts = 0;
 3150:     $result.='<table border="0">';
 3151:     my %seen = ();
 3152:     my @part_response_id = &flatten_responseType($responseType);
 3153:     foreach my $part_response_id (@part_response_id) {
 3154:     	my ($partid,$respid) = @{ $part_response_id };
 3155: 	my $part_resp = join('_',@{ $part_response_id });
 3156: 	next if $seen{$partid};
 3157: 	$seen{$partid}++;
 3158: 	my $handgrade=$$handgrade{$part_resp};
 3159: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3160: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3161: 
 3162: 	$result.='<input type="hidden" name="partid_'.
 3163: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3164: 	$result.='<input type="hidden" name="weight_'.
 3165: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3166: 	my $display_part=&get_display_part($partid,$symb);
 3167: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
 3168: 	$result.='<table border="0"><tr>';  
 3169: 	my $ctr = 0;
 3170: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3171: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3172: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3173: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3174: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3175: 	    $ctr++;
 3176: 	}
 3177: 	$result.='</tr></table>';
 3178: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
 3179: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3180: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3181: 	    $weight{$partid}.' (problem weight)</td>'."\n";
 3182: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
 3183: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3184: 		$weight{$partid}.')"> '.
 3185: 	    '<option selected="selected"> </option>'.
 3186: 	    '<option>excused</option>'.
 3187: 	    '<option>reset status</option></select></td>'.
 3188:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
 3189: 	$ctsparts++;
 3190:     }
 3191:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
 3192: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3193:     $result.='<input type="button" value="Revert to Default" '.
 3194: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
 3195: 
 3196:     #table listing all the students in a section/class
 3197:     #header of table
 3198:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
 3199:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
 3200: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
 3201: 	'<td>'.&nameUserString('header')."</td>\n";
 3202:     my (@parts) = sort(&getpartlist($symb));
 3203:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3204:     my @partids = ();
 3205:     foreach my $part (@parts) {
 3206: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3207: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
 3208: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3209: 	my ($partid) = &split_part_type($part);
 3210:         push(@partids, $partid);
 3211: 	my $display_part=&get_display_part($partid,$symb);
 3212: 	if ($display =~ /^Partial Credit Factor/) {
 3213: 	    $result.='<td><b>Score Part:</b> '.$display_part.
 3214: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
 3215: 	    next;
 3216: 	} else {
 3217: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
 3218: 	}
 3219: 	$display =~ s|Problem Status|Grade Status<br />|;
 3220: 	$result.='<td><b>'.$display.'</td>'."\n";
 3221:     }
 3222:     $result.='</tr>';
 3223: 
 3224:     my %last_resets = 
 3225: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3226: 
 3227:     #get info for each student
 3228:     #list all the students - with points and grade status
 3229:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3230:     my $ctr = 0;
 3231:     foreach (sort 
 3232: 	     {
 3233: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3234: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3235: 		 }
 3236: 		 return $a cmp $b;
 3237: 	     } (keys(%$fullname))) {
 3238: 	$ctr++;
 3239: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3240: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3241:     }
 3242:     $result.='</table></td></tr></table>';
 3243:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3244:     $result.='<input type="button" value="Save" '.
 3245: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3246:     if (scalar(%$fullname) eq 0) {
 3247: 	my $colspan=3+scalar(@parts);
 3248: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3249:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3250: 	$result='<span class="LC_warning">'.
 3251: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
 3252: 	        $section_display, $stu_status).
 3253: 	    '</span>';
 3254:     }
 3255:     $result.=&show_grading_menu_form($symb);
 3256:     return $result;
 3257: }
 3258: 
 3259: #--- call by previous routine to display each student
 3260: sub viewstudentgrade {
 3261:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3262:     my ($uname,$udom) = split(/:/,$student);
 3263:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3264:     my %aggregates = (); 
 3265:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
 3266: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3267: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3268: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3269: 	'\');" target="_self">'.$fullname.'</a> '.
 3270: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3271:     $student=~s/:/_/; # colon doen't work in javascript for names
 3272:     foreach my $apart (@$parts) {
 3273: 	my ($part,$type) = &split_part_type($apart);
 3274: 	my $score=$record{"resource.$part.$type"};
 3275:         $result.='<td align="center">';
 3276:         my ($aggtries,$totaltries);
 3277:         unless (exists($aggregates{$part})) {
 3278: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3279: 
 3280: 	    $aggtries = $totaltries;
 3281:             if ($$last_resets{$part}) {  
 3282:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3283: 					   $part);
 3284:             }
 3285:             $result.='<input type="hidden" name="'.
 3286:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3287:             $result.='<input type="hidden" name="'.
 3288:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3289:             $aggregates{$part} = 1;
 3290:         }
 3291: 	if ($type eq 'awarded') {
 3292: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3293: 	    $result.='<input type="hidden" name="'.
 3294: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3295: 	    $result.='<input type="text" name="'.
 3296: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3297: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3298: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3299: 	} elsif ($type eq 'solved') {
 3300: 	    my ($status,$foo)=split(/_/,$score,2);
 3301: 	    $status = 'nothing' if ($status eq '');
 3302: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3303: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3304: 	    $result.='&nbsp;<select name="'.
 3305: 		'GD_'.$student.'_'.$part.'_solved" '.
 3306: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3307: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
 3308: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
 3309: 	    $result.='<option>reset status</option>';
 3310: 	    $result.="</select>&nbsp;</td>\n";
 3311: 	} else {
 3312: 	    $result.='<input type="hidden" name="'.
 3313: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3314: 		    "\n";
 3315: 	    $result.='<input type="text" name="'.
 3316: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3317: 		'value="'.$score.'" size="4" /></td>'."\n";
 3318: 	}
 3319:     }
 3320:     $result.='</tr>';
 3321:     return $result;
 3322: }
 3323: 
 3324: #--- change scores for all the students in a section/class
 3325: #    record does not get update if unchanged
 3326: sub editgrades {
 3327:     my ($request) = @_;
 3328: 
 3329:     my $symb=&get_symb($request);
 3330:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3331:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
 3332:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
 3333:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3334: 
 3335:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
 3336:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
 3337: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
 3338: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
 3339: 
 3340:     my %scoreptr = (
 3341: 		    'correct'  =>'correct_by_override',
 3342: 		    'incorrect'=>'incorrect_by_override',
 3343: 		    'excused'  =>'excused',
 3344: 		    'ungraded' =>'ungraded_attempted',
 3345: 		    'nothing'  => '',
 3346: 		    );
 3347:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3348: 
 3349:     my (@partid);
 3350:     my %weight = ();
 3351:     my %columns = ();
 3352:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3353: 
 3354:     my (@parts) = sort(&getpartlist($symb));
 3355:     my $header;
 3356:     while ($ctr < $env{'form.totalparts'}) {
 3357: 	my $partid = $env{'form.partid_'.$ctr};
 3358: 	push @partid,$partid;
 3359: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3360: 	$ctr++;
 3361:     }
 3362:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3363:     foreach my $partid (@partid) {
 3364: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
 3365: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
 3366: 	$columns{$partid}=2;
 3367: 	foreach my $stores (@parts) {
 3368: 	    my ($part,$type) = &split_part_type($stores);
 3369: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3370: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3371: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3372: 	    $display =~ s/\[Part: (\w)+\]//;
 3373: 	    $display =~ s/Number of Attempts/Tries/;
 3374: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
 3375: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
 3376: 	    $columns{$partid}+=2;
 3377: 	}
 3378:     }
 3379:     foreach my $partid (@partid) {
 3380: 	my $display_part=&get_display_part($partid,$symb);
 3381: 	$result .= '<td colspan="'.$columns{$partid}.
 3382: 	    '" align="center"><b>Part:</b> '.$display_part.
 3383: 	    ' (Weight = '.$weight{$partid}.')</td>';
 3384: 
 3385:     }
 3386:     $result .= '</tr><tr bgcolor="#deffff">';
 3387:     $result .= $header;
 3388:     $result .= '</tr>'."\n";
 3389:     my $noupdate;
 3390:     my ($updateCtr,$noupdateCtr) = (1,1);
 3391:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3392: 	my $line;
 3393: 	my $user = $env{'form.ctr'.$i};
 3394: 	my ($uname,$udom)=split(/:/,$user);
 3395: 	my %newrecord;
 3396: 	my $updateflag = 0;
 3397: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3398: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3399: 	if (!&canmodify($usec)) {
 3400: 	    my $numcols=scalar(@partid)*4+2;
 3401: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
 3402: 	    next;
 3403: 	}
 3404:         my %aggregate = ();
 3405:         my $aggregateflag = 0;
 3406: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3407: 	foreach (@partid) {
 3408: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3409: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3410: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3411: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3412: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3413: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3414: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3415: 	    my $score;
 3416: 	    if ($partial eq '') {
 3417: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3418: 	    } elsif ($partial > 0) {
 3419: 		$score = 'correct_by_override';
 3420: 	    } elsif ($partial == 0) {
 3421: 		$score = 'incorrect_by_override';
 3422: 	    }
 3423: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3424: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3425: 
 3426: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3427: 		"$env{'user.name'}:$env{'user.domain'}";
 3428: 	    if ($dropMenu eq 'reset status' &&
 3429: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3430: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3431: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3432: 		$newrecord{'resource.'.$_.'.award'} = '';
 3433: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3434: 		$updateflag = 1;
 3435:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3436:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3437:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3438:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3439:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3440:                     $aggregateflag = 1;
 3441:                 }
 3442: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3443: 		$updateflag = 1;
 3444: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3445: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3446: 		$rec_update++;
 3447: 	    }
 3448: 
 3449: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3450: 		'<td align="center">'.$awarded.
 3451: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3452: 
 3453: 
 3454: 	    my $partid=$_;
 3455: 	    foreach my $stores (@parts) {
 3456: 		my ($part,$type) = &split_part_type($stores);
 3457: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3458: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3459: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3460: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3461: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3462: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3463: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3464: 		    $updateflag=1;
 3465: 		}
 3466: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3467: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3468: 	    }
 3469: 	}
 3470: 	$line.='</tr>'."\n";
 3471: 
 3472: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3473: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3474: 
 3475: 	if ($updateflag) {
 3476: 	    $count++;
 3477: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3478: 				    $udom,$uname);
 3479: 
 3480: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3481: 					      $cnum,$udom,$uname)) {
 3482: 		# need to figure out if should be in queue.
 3483: 		my %record =  
 3484: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3485: 					     $udom,$uname);
 3486: 		my $all_graded = 1;
 3487: 		my $none_graded = 1;
 3488: 		foreach my $part (@parts) {
 3489: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3490: 			$all_graded = 0;
 3491: 		    } else {
 3492: 			$none_graded = 0;
 3493: 		    }
 3494: 		}
 3495: 
 3496: 		if ($all_graded || $none_graded) {
 3497: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3498: 							   $symb,$cdom,$cnum,
 3499: 							   $udom,$uname);
 3500: 		}
 3501: 	    }
 3502: 
 3503: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
 3504: 	    $updateCtr++;
 3505: 	} else {
 3506: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
 3507: 	    $noupdateCtr++;
 3508: 	}
 3509:         if ($aggregateflag) {
 3510:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3511: 				  $cdom,$cnum);
 3512:         }
 3513:     }
 3514:     if ($noupdate) {
 3515: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3516: 	my $numcols=scalar(@partid)*4+2;
 3517: 	$result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr><tr bgcolor="#ffffde">'.$noupdate;
 3518:     }
 3519:     $result .= '</table></td></tr></table>'."\n".
 3520: 	&show_grading_menu_form ($symb);
 3521:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
 3522: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
 3523: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
 3524:     return $title.$msg.$result;
 3525: }
 3526: 
 3527: sub split_part_type {
 3528:     my ($partstr) = @_;
 3529:     my ($temp,@allparts)=split(/_/,$partstr);
 3530:     my $type=pop(@allparts);
 3531:     my $part=join('_',@allparts);
 3532:     return ($part,$type);
 3533: }
 3534: 
 3535: #------------- end of section for handling grading by section/class ---------
 3536: #
 3537: #----------------------------------------------------------------------------
 3538: 
 3539: 
 3540: #----------------------------------------------------------------------------
 3541: #
 3542: #-------------------------- Next few routines handles grading by csv upload
 3543: #
 3544: #--- Javascript to handle csv upload
 3545: sub csvupload_javascript_reverse_associate {
 3546:     my $error1=&mt('You need to specify the username or ID');
 3547:     my $error2=&mt('You need to specify at least one grading field');
 3548:   return(<<ENDPICK);
 3549:   function verify(vf) {
 3550:     var foundsomething=0;
 3551:     var founduname=0;
 3552:     var foundID=0;
 3553:     for (i=0;i<=vf.nfields.value;i++) {
 3554:       tw=eval('vf.f'+i+'.selectedIndex');
 3555:       if (i==0 && tw!=0) { foundID=1; }
 3556:       if (i==1 && tw!=0) { founduname=1; }
 3557:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3558:     }
 3559:     if (founduname==0 && foundID==0) {
 3560: 	alert('$error1');
 3561: 	return;
 3562:     }
 3563:     if (foundsomething==0) {
 3564: 	alert('$error2');
 3565: 	return;
 3566:     }
 3567:     vf.submit();
 3568:   }
 3569:   function flip(vf,tf) {
 3570:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3571:     var i;
 3572:     for (i=0;i<=vf.nfields.value;i++) {
 3573:       //can not pick the same destination field for both name and domain
 3574:       if (((i ==0)||(i ==1)) && 
 3575:           ((tf==0)||(tf==1)) && 
 3576:           (i!=tf) &&
 3577:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3578:         eval('vf.f'+i+'.selectedIndex=0;')
 3579:       }
 3580:     }
 3581:   }
 3582: ENDPICK
 3583: }
 3584: 
 3585: sub csvupload_javascript_forward_associate {
 3586:     my $error1=&mt('You need to specify the username or ID');
 3587:     my $error2=&mt('You need to specify at least one grading field');
 3588:   return(<<ENDPICK);
 3589:   function verify(vf) {
 3590:     var foundsomething=0;
 3591:     var founduname=0;
 3592:     var foundID=0;
 3593:     for (i=0;i<=vf.nfields.value;i++) {
 3594:       tw=eval('vf.f'+i+'.selectedIndex');
 3595:       if (tw==1) { foundID=1; }
 3596:       if (tw==2) { founduname=1; }
 3597:       if (tw>3) { foundsomething=1; }
 3598:     }
 3599:     if (founduname==0 && foundID==0) {
 3600: 	alert('$error1');
 3601: 	return;
 3602:     }
 3603:     if (foundsomething==0) {
 3604: 	alert('$error2');
 3605: 	return;
 3606:     }
 3607:     vf.submit();
 3608:   }
 3609:   function flip(vf,tf) {
 3610:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3611:     var i;
 3612:     //can not pick the same destination field twice
 3613:     for (i=0;i<=vf.nfields.value;i++) {
 3614:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3615:         eval('vf.f'+i+'.selectedIndex=0;')
 3616:       }
 3617:     }
 3618:   }
 3619: ENDPICK
 3620: }
 3621: 
 3622: sub csvuploadmap_header {
 3623:     my ($request,$symb,$datatoken,$distotal)= @_;
 3624:     my $javascript;
 3625:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3626: 	$javascript=&csvupload_javascript_reverse_associate();
 3627:     } else {
 3628: 	$javascript=&csvupload_javascript_forward_associate();
 3629:     }
 3630: 
 3631:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3632:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3633:     my $ignore=&mt('Ignore First Line');
 3634:     $symb = &Apache::lonenc::check_encrypt($symb);
 3635:     $request->print(<<ENDPICK);
 3636: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3637: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3638: $result
 3639: <hr />
 3640: <h3>Identify fields</h3>
 3641: Total number of records found in file: $distotal <hr />
 3642: Enter as many fields as you can. The system will inform you and bring you back
 3643: to this page if the data selected is insufficient to run your class.<hr />
 3644: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3645: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3646: <input type="hidden" name="associate"  value="" />
 3647: <input type="hidden" name="phase"      value="three" />
 3648: <input type="hidden" name="datatoken"  value="$datatoken" />
 3649: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3650: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3651: <input type="hidden" name="upfile_associate" 
 3652:                                        value="$env{'form.upfile_associate'}" />
 3653: <input type="hidden" name="symb"       value="$symb" />
 3654: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3655: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3656: <input type="hidden" name="command"    value="csvuploadoptions" />
 3657: <hr />
 3658: <script type="text/javascript" language="Javascript">
 3659: $javascript
 3660: </script>
 3661: ENDPICK
 3662:     return '';
 3663: 
 3664: }
 3665: 
 3666: sub csvupload_fields {
 3667:     my ($symb) = @_;
 3668:     my (@parts) = &getpartlist($symb);
 3669:     my @fields=(['ID','Student ID'],
 3670: 		['username','Student Username'],
 3671: 		['domain','Student Domain']);
 3672:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3673:     foreach my $part (sort(@parts)) {
 3674: 	my @datum;
 3675: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3676: 	my $name=$part;
 3677: 	if  (!$display) { $display = $name; }
 3678: 	@datum=($name,$display);
 3679: 	if ($name=~/^stores_(.*)_awarded/) {
 3680: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3681: 	}
 3682: 	push(@fields,\@datum);
 3683:     }
 3684:     return (@fields);
 3685: }
 3686: 
 3687: sub csvuploadmap_footer {
 3688:     my ($request,$i,$keyfields) =@_;
 3689:     $request->print(<<ENDPICK);
 3690: </table>
 3691: <input type="hidden" name="nfields" value="$i" />
 3692: <input type="hidden" name="keyfields" value="$keyfields" />
 3693: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3694: </form>
 3695: ENDPICK
 3696: }
 3697: 
 3698: sub checkforfile_js {
 3699:     my $result =<<CSVFORMJS;
 3700: <script type="text/javascript" language="javascript">
 3701:     function checkUpload(formname) {
 3702: 	if (formname.upfile.value == "") {
 3703: 	    alert("Please use the browse button to select a file from your local directory.");
 3704: 	    return false;
 3705: 	}
 3706: 	formname.submit();
 3707:     }
 3708:     </script>
 3709: CSVFORMJS
 3710:     return $result;
 3711: }
 3712: 
 3713: sub upcsvScores_form {
 3714:     my ($request) = shift;
 3715:     my ($symb)=&get_symb($request);
 3716:     if (!$symb) {return '';}
 3717:     my $result=&checkforfile_js();
 3718:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3719:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3720:     $result.=$table;
 3721:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3722:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3723:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
 3724: 	'.</b></td></tr>'."\n";
 3725:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3726:     my $upload=&mt("Upload Scores");
 3727:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3728:     my $ignore=&mt('Ignore First Line');
 3729:     $symb = &Apache::lonenc::check_encrypt($symb);
 3730:     $result.=<<ENDUPFORM;
 3731: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3732: <input type="hidden" name="symb" value="$symb" />
 3733: <input type="hidden" name="command" value="csvuploadmap" />
 3734: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3735: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3736: $upfile_select
 3737: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3738: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3739: </form>
 3740: ENDUPFORM
 3741:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3742:                            &mt("How do I create a CSV file from a spreadsheet"))
 3743:     .'</td></tr></table>'."\n";
 3744:     $result.='</td></tr></table><br /><br />'."\n";
 3745:     $result.=&show_grading_menu_form($symb);
 3746:     return $result;
 3747: }
 3748: 
 3749: 
 3750: sub csvuploadmap {
 3751:     my ($request)= @_;
 3752:     my ($symb)=&get_symb($request);
 3753:     if (!$symb) {return '';}
 3754: 
 3755:     my $datatoken;
 3756:     if (!$env{'form.datatoken'}) {
 3757: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3758:     } else {
 3759: 	$datatoken=$env{'form.datatoken'};
 3760: 	&Apache::loncommon::load_tmp_file($request);
 3761:     }
 3762:     my @records=&Apache::loncommon::upfile_record_sep();
 3763:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3764:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3765:     my ($i,$keyfields);
 3766:     if (@records) {
 3767: 	my @fields=&csvupload_fields($symb);
 3768: 
 3769: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3770: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3771: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3772: 							  \@fields);
 3773: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3774: 	    chop($keyfields);
 3775: 	} else {
 3776: 	    unshift(@fields,['none','']);
 3777: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3778: 							    \@fields);
 3779:             foreach my $rec (@records) {
 3780:                 my %temp = &Apache::loncommon::record_sep($rec);
 3781:                 if (%temp) {
 3782:                     $keyfields=join(',',sort(keys(%temp)));
 3783:                     last;
 3784:                 }
 3785:             }
 3786: 	}
 3787:     }
 3788:     &csvuploadmap_footer($request,$i,$keyfields);
 3789:     $request->print(&show_grading_menu_form($symb));
 3790: 
 3791:     return '';
 3792: }
 3793: 
 3794: sub csvuploadoptions {
 3795:     my ($request)= @_;
 3796:     my ($symb)=&get_symb($request);
 3797:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3798:     my $ignore=&mt('Ignore First Line');
 3799:     $request->print(<<ENDPICK);
 3800: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3801: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3802: <input type="hidden" name="command"    value="csvuploadassign" />
 3803: <!--
 3804: <p>
 3805: <label>
 3806:    <input type="checkbox" name="show_full_results" />
 3807:    Show a table of all changes
 3808: </label>
 3809: </p>
 3810: -->
 3811: <p>
 3812: <label>
 3813:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3814:    Overwrite any existing score
 3815: </label>
 3816: </p>
 3817: ENDPICK
 3818:     my %fields=&get_fields();
 3819:     if (!defined($fields{'domain'})) {
 3820: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3821: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3822:     }
 3823:     foreach my $key (sort(keys(%env))) {
 3824: 	if ($key !~ /^form\.(.*)$/) { next; }
 3825: 	my $cleankey=$1;
 3826: 	if ($cleankey eq 'command') { next; }
 3827: 	$request->print('<input type="hidden" name="'.$cleankey.
 3828: 			'"  value="'.$env{$key}.'" />'."\n");
 3829:     }
 3830:     # FIXME do a check for any duplicated user ids...
 3831:     # FIXME do a check for any invalid user ids?...
 3832:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3833: <hr /></form>'."\n");
 3834:     $request->print(&show_grading_menu_form($symb));
 3835:     return '';
 3836: }
 3837: 
 3838: sub get_fields {
 3839:     my %fields;
 3840:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3841:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3842: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3843: 	    if ($env{'form.f'.$i} ne 'none') {
 3844: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3845: 	    }
 3846: 	} else {
 3847: 	    if ($env{'form.f'.$i} ne 'none') {
 3848: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3849: 	    }
 3850: 	}
 3851:     }
 3852:     return %fields;
 3853: }
 3854: 
 3855: sub csvuploadassign {
 3856:     my ($request)= @_;
 3857:     my ($symb)=&get_symb($request);
 3858:     if (!$symb) {return '';}
 3859:     my $error_msg = '';
 3860:     &Apache::loncommon::load_tmp_file($request);
 3861:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 3862:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 3863:     my %fields=&get_fields();
 3864:     $request->print('<h3>Assigning Grades</h3>');
 3865:     my $courseid=$env{'request.course.id'};
 3866:     my ($classlist) = &getclasslist('all',0);
 3867:     my @notallowed;
 3868:     my @skipped;
 3869:     my $countdone=0;
 3870:     foreach my $grade (@gradedata) {
 3871: 	my %entries=&Apache::loncommon::record_sep($grade);
 3872: 	my $domain;
 3873: 	if ($entries{$fields{'domain'}}) {
 3874: 	    $domain=$entries{$fields{'domain'}};
 3875: 	} else {
 3876: 	    $domain=$env{'form.default_domain'};
 3877: 	}
 3878: 	$domain=~s/\s//g;
 3879: 	my $username=$entries{$fields{'username'}};
 3880: 	$username=~s/\s//g;
 3881: 	if (!$username) {
 3882: 	    my $id=$entries{$fields{'ID'}};
 3883: 	    $id=~s/\s//g;
 3884: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 3885: 	    $username=$ids{$id};
 3886: 	}
 3887: 	if (!exists($$classlist{"$username:$domain"})) {
 3888: 	    my $id=$entries{$fields{'ID'}};
 3889: 	    $id=~s/\s//g;
 3890: 	    if ($id) {
 3891: 		push(@skipped,"$id:$domain");
 3892: 	    } else {
 3893: 		push(@skipped,"$username:$domain");
 3894: 	    }
 3895: 	    next;
 3896: 	}
 3897: 	my $usec=$classlist->{"$username:$domain"}[5];
 3898: 	if (!&canmodify($usec)) {
 3899: 	    push(@notallowed,"$username:$domain");
 3900: 	    next;
 3901: 	}
 3902: 	my %points;
 3903: 	my %grades;
 3904: 	foreach my $dest (keys(%fields)) {
 3905: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 3906: 		$dest eq 'domain') { next; }
 3907: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 3908: 	    if ($dest=~/stores_(.*)_points/) {
 3909: 		my $part=$1;
 3910: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 3911: 					      $symb,$domain,$username);
 3912:                 if ($wgt) {
 3913:                     $entries{$fields{$dest}}=~s/\s//g;
 3914:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 3915:                     my $award=($pcr == 0) ? 'incorrect_by_override'
 3916:                                           : 'correct_by_override';
 3917:                     $grades{"resource.$part.awarded"}=$pcr;
 3918:                     $grades{"resource.$part.solved"}=$award;
 3919:                     $points{$part}=1;
 3920:                 } else {
 3921:                     $error_msg = "<br />" .
 3922:                         &mt("Some point values were assigned"
 3923:                             ." for problems with a weight "
 3924:                             ."of zero. These values were "
 3925:                             ."ignored.");
 3926:                 }
 3927: 	    } else {
 3928: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 3929: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 3930: 		my $store_key=$dest;
 3931: 		$store_key=~s/^stores/resource/;
 3932: 		$store_key=~s/_/\./g;
 3933: 		$grades{$store_key}=$entries{$fields{$dest}};
 3934: 	    }
 3935: 	}
 3936: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
 3937: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 3938: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
 3939: 					   $env{'request.course.id'},
 3940: 					   $domain,$username);
 3941: 	if ($result eq 'ok') {
 3942: 	    $request->print('.');
 3943: 	} else {
 3944: 	    $request->print("<p>
 3945:                               <span class=\"LC_error\">
 3946:                                  Failed to save student $username:$domain.
 3947:                                  Message when trying to save was ($result)
 3948:                               </span>
 3949:                              </p>" );
 3950: 	}
 3951: 	$request->rflush();
 3952: 	$countdone++;
 3953:     }
 3954:     $request->print("<br />Saved $countdone students\n");
 3955:     if (@skipped) {
 3956: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
 3957: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 3958:     }
 3959:     if (@notallowed) {
 3960: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
 3961: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 3962:     }
 3963:     $request->print("<br />\n");
 3964:     $request->print(&show_grading_menu_form($symb));
 3965:     return $error_msg;
 3966: }
 3967: #------------- end of section for handling csv file upload ---------
 3968: #
 3969: #-------------------------------------------------------------------
 3970: #
 3971: #-------------- Next few routines handle grading by page/sequence
 3972: #
 3973: #--- Select a page/sequence and a student to grade
 3974: sub pickStudentPage {
 3975:     my ($request) = shift;
 3976: 
 3977:     $request->print(<<LISTJAVASCRIPT);
 3978: <script type="text/javascript" language="javascript">
 3979: 
 3980: function checkPickOne(formname) {
 3981:     if (radioSelection(formname.student) == null) {
 3982: 	alert("Please select the student you wish to grade.");
 3983: 	return;
 3984:     }
 3985:     ptr = pullDownSelection(formname.selectpage);
 3986:     formname.page.value = formname["page"+ptr].value;
 3987:     formname.title.value = formname["title"+ptr].value;
 3988:     formname.submit();
 3989: }
 3990: 
 3991: </script>
 3992: LISTJAVASCRIPT
 3993:     &commonJSfunctions($request);
 3994:     my ($symb) = &get_symb($request);
 3995:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 3996:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 3997:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 3998: 
 3999:     my $result='<h3><span class="LC_info">&nbsp;'.
 4000: 	'Manual Grading by Page or Sequence</span></h3>';
 4001: 
 4002:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 4003:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
 4004:     my ($titles,$symbx) = &getSymbMap();
 4005:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 4006: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 4007: #    my $type=($curpage =~ /\.(page|sequence)/);
 4008:     my $ctr=0;
 4009:     foreach (@$titles) {
 4010: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4011: 	$result.='<option value="'.$ctr.'" '.
 4012: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4013: 	    '>'.$showtitle.'</option>'."\n";
 4014: 	$ctr++;
 4015:     }
 4016:     $result.= '</select>'."<br />\n";
 4017:     $ctr=0;
 4018:     foreach (@$titles) {
 4019: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4020: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 4021: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 4022: 	$ctr++;
 4023:     }
 4024:     $result.='<input type="hidden" name="page" />'."\n".
 4025: 	'<input type="hidden" name="title" />'."\n";
 4026: 
 4027:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
 4028: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
 4029: 
 4030:     $result.='&nbsp;<b>Submission Details: </b>'.
 4031: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
 4032: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
 4033: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
 4034:     
 4035:     $result.=&build_section_inputs();
 4036:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4037:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4038: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4039: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4040: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4041: 
 4042:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
 4043: 	'<input type="text" name="CODE" value="" /><br />'."\n";
 4044: 
 4045:     $result.='&nbsp;<input type="button" '.
 4046: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
 4047: 
 4048:     $request->print($result);
 4049: 
 4050:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
 4051: 	'<table border="0"><tr><td bgcolor="#777777">'.
 4052: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 4053: 	'<td align="right">&nbsp;<b>No.</b></td>'.
 4054: 	'<td>'.&nameUserString('header').'</td>'.
 4055: 	'<td align="right">&nbsp;<b>No.</b></td>'.
 4056: 	'<td>'.&nameUserString('header').'</td></tr>';
 4057:  
 4058:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4059:     my $ptr = 1;
 4060:     foreach my $student (sort 
 4061: 			 {
 4062: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4063: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4064: 			     }
 4065: 			     return $a cmp $b;
 4066: 			 } (keys(%$fullname))) {
 4067: 	my ($uname,$udom) = split(/:/,$student);
 4068: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
 4069: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4070: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4071: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4072: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
 4073: 	$ptr++;
 4074:     }
 4075:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
 4076:     $studentTable.='</table></td></tr></table>'."\n";
 4077:     $studentTable.='<input type="button" '.
 4078: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
 4079: 
 4080:     $studentTable.=&show_grading_menu_form($symb);
 4081:     $request->print($studentTable);
 4082: 
 4083:     return '';
 4084: }
 4085: 
 4086: sub getSymbMap {
 4087:     my $navmap = Apache::lonnavmaps::navmap->new();
 4088: 
 4089:     my %symbx = ();
 4090:     my @titles = ();
 4091:     my $minder = 0;
 4092: 
 4093:     # Gather every sequence that has problems.
 4094:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4095: 					       1,0,1);
 4096:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4097: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4098: 	    my $title = $minder.'.'.
 4099: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4100: 	    push(@titles, $title); # minder in case two titles are identical
 4101: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4102: 	    $minder++;
 4103: 	}
 4104:     }
 4105:     return \@titles,\%symbx;
 4106: }
 4107: 
 4108: #
 4109: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4110: sub displayPage {
 4111:     my ($request) = shift;
 4112: 
 4113:     my ($symb) = &get_symb($request);
 4114:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4115:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4116:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4117:     my $pageTitle = $env{'form.page'};
 4118:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4119:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4120:     my $usec=$classlist->{$env{'form.student'}}[5];
 4121: 
 4122:     #need to make sure we have the correct data for later EXT calls, 
 4123:     #thus invalidate the cache
 4124:     &Apache::lonnet::devalidatecourseresdata(
 4125:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4126:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4127:     &Apache::lonnet::clear_EXT_cache_status();
 4128: 
 4129:     if (!&canview($usec)) {
 4130: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
 4131: 	$request->print(&show_grading_menu_form($symb));
 4132: 	return;
 4133:     }
 4134:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4135:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
 4136: 	'</h3>'."\n";
 4137:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4138: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
 4139:     } else {
 4140: 	delete($env{'form.CODE'});
 4141:     }
 4142:     &sub_page_js($request);
 4143:     $request->print($result);
 4144: 
 4145:     my $navmap = Apache::lonnavmaps::navmap->new();
 4146:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4147:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4148:     if (!$map) {
 4149: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
 4150: 	$request->print(&show_grading_menu_form($symb));
 4151: 	return; 
 4152:     }
 4153:     my $iterator = $navmap->getIterator($map->map_start(),
 4154: 					$map->map_finish());
 4155: 
 4156:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4157: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4158: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4159: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4160: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4161: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4162: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4163: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4164: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4165: 
 4166:     if (defined($env{'form.CODE'})) {
 4167: 	$studentTable.=
 4168: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4169:     }
 4170:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4171: 	'" src="'.$request->dir_config('lonIconsURL').
 4172: 	'/check.gif" height="16" border="0" />';
 4173: 
 4174:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
 4175: 	' symbol.'."\n".
 4176: 	'<table border="0"><tr><td bgcolor="#777777">'.
 4177: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 4178: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
 4179: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
 4180: 
 4181:     &Apache::lonxml::clear_problem_counter();
 4182:     my ($depth,$question,$prob) = (1,1,1);
 4183:     $iterator->next(); # skip the first BEGIN_MAP
 4184:     my $curRes = $iterator->next(); # for "current resource"
 4185:     while ($depth > 0) {
 4186:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4187:         if($curRes == $iterator->END_MAP) { $depth--; }
 4188: 
 4189:         if (ref($curRes) && $curRes->is_problem()) {
 4190: 	    my $parts = $curRes->parts();
 4191:             my $title = $curRes->compTitle();
 4192: 	    my $symbx = $curRes->symb();
 4193: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
 4194: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
 4195: 	    $studentTable.='<td valign="top">';
 4196: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4197: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4198: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4199: 					     undef,'both',\%form);
 4200: 	    } else {
 4201: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4202: 		$companswer =~ s|<form(.*?)>||g;
 4203: 		$companswer =~ s|</form>||g;
 4204: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4205: #		    $companswer =~ s/$1/ /ms;
 4206: #		    $request->print('match='.$1."<br />\n");
 4207: #		}
 4208: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4209: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
 4210: 	    }
 4211: 
 4212: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4213: 
 4214: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4215: 		if ($record{'version'} eq '') {
 4216: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
 4217: 		} else {
 4218: 		    my %responseType = ();
 4219: 		    foreach my $partid (@{$parts}) {
 4220: 			my @responseIds =$curRes->responseIds($partid);
 4221: 			my @responseType =$curRes->responseType($partid);
 4222: 			my %responseIds;
 4223: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4224: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4225: 			}
 4226: 			$responseType{$partid} = \%responseIds;
 4227: 		    }
 4228: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4229: 
 4230: 		}
 4231: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4232: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4233: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4234: 									$env{'request.course.id'},
 4235: 									'','.submission');
 4236:  
 4237: 	    }
 4238: 	    if (&canmodify($usec)) {
 4239: 		foreach my $partid (@{$parts}) {
 4240: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4241: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4242: 		    $question++;
 4243: 		}
 4244: 		$prob++;
 4245: 	    }
 4246: 	    $studentTable.='</td></tr>';
 4247: 
 4248: 	}
 4249:         $curRes = $iterator->next();
 4250:     }
 4251: 
 4252:     $studentTable.='</table></td></tr></table>'."\n".
 4253: 	'<input type="button" value="Save" '.
 4254: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4255: 	'</form>'."\n";
 4256:     $studentTable.=&show_grading_menu_form($symb);
 4257:     $request->print($studentTable);
 4258: 
 4259:     return '';
 4260: }
 4261: 
 4262: sub displaySubByDates {
 4263:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4264:     my $isCODE=0;
 4265:     my $isTask = ($symb =~/\.task$/);
 4266:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4267:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
 4268: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
 4269: 	'<td><b>Date/Time</b></td>'.
 4270: 	($isCODE?'<td><b>CODE</b></td>':'').
 4271: 	'<td><b>Submission</b></td>'.
 4272: 	'<td><b>Status&nbsp;</b></td></tr>';
 4273:     my ($version);
 4274:     my %mark;
 4275:     my %orders;
 4276:     $mark{'correct_by_student'} = $checkIcon;
 4277:     if (!exists($$record{'1:timestamp'})) {
 4278: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
 4279:     }
 4280: 
 4281:     my $interaction;
 4282:     for ($version=1;$version<=$$record{'version'};$version++) {
 4283: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
 4284: 	if (exists($$record{$version.':resource.0.version'})) {
 4285: 	    $interaction = $$record{$version.':resource.0.version'};
 4286: 	}
 4287: 
 4288: 	my $where = ($isTask ? "$version:resource.$interaction"
 4289: 		             : "$version:resource");
 4290: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
 4291: 	if ($isCODE) {
 4292: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4293: 	}
 4294: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4295: 	my @displaySub = ();
 4296: 	foreach my $partid (@{$parts}) {
 4297: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4298: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4299: 	    
 4300: 
 4301: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4302: 	    my $display_part=&get_display_part($partid,$symb);
 4303: 	    foreach my $matchKey (@matchKey) {
 4304: 		if (exists($$record{$version.':'.$matchKey}) &&
 4305: 		    $$record{$version.':'.$matchKey} ne '') {
 4306: 
 4307: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4308: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4309: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
 4310: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
 4311: 			$responseId.')</span>&nbsp;<b>';
 4312: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4313: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
 4314: 		    } else {
 4315: 			$displaySub[0].='Trial&nbsp;'.
 4316: 			    $$record{"$where.$partid.tries"};
 4317: 		    }
 4318: 		    my $responseType=($isTask ? 'Task'
 4319:                                               : $responseType->{$partid}->{$responseId});
 4320: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4321: 		    if (!exists($orders{$partid}->{$responseId})) {
 4322: 			$orders{$partid}->{$responseId}=
 4323: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
 4324: 		    }
 4325: 		    $displaySub[0].='</b>&nbsp; '.
 4326: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4327: 		}
 4328: 	    }
 4329: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4330: 		$displaySub[1].='Checked in by '.
 4331: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
 4332: 		    $$record{"$where.$partid.checkedin.slot"}.
 4333: 		    '<br />';
 4334: 	    }
 4335: 	    if (exists $$record{"$where.$partid.award"}) {
 4336: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
 4337: 		    lc($$record{"$where.$partid.award"}).' '.
 4338: 		    $mark{$$record{"$where.$partid.solved"}}.
 4339: 		    '<br />';
 4340: 	    }
 4341: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4342: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4343: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4344: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4345: 		$displaySub[2].=
 4346: 		    $$record{"$version:resource.$partid.regrader"}.
 4347: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4348: 	    }
 4349: 	}
 4350: 	# needed because old essay regrader has not parts info
 4351: 	if (exists $$record{"$version:resource.regrader"}) {
 4352: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4353: 	}
 4354: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4355: 	if ($displaySub[2]) {
 4356: 	    $studentTable.='Manually graded by '.$displaySub[2];
 4357: 	}
 4358: 	$studentTable.='&nbsp;</td></tr>';
 4359:     
 4360:     }
 4361:     $studentTable.='</table></td></tr></table>';
 4362:     return $studentTable;
 4363: }
 4364: 
 4365: sub updateGradeByPage {
 4366:     my ($request) = shift;
 4367: 
 4368:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4369:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4370:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4371:     my $pageTitle = $env{'form.page'};
 4372:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4373:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4374:     my $usec=$classlist->{$env{'form.student'}}[5];
 4375:     if (!&canmodify($usec)) {
 4376: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
 4377: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4378: 	return;
 4379:     }
 4380:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4381:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4382: 	'</h3>'."\n";
 4383: 
 4384:     $request->print($result);
 4385: 
 4386:     my $navmap = Apache::lonnavmaps::navmap->new();
 4387:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4388:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4389:     if (!$map) {
 4390: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
 4391: 	my ($symb)=&get_symb($request);
 4392: 	$request->print(&show_grading_menu_form($symb));
 4393: 	return; 
 4394:     }
 4395:     my $iterator = $navmap->getIterator($map->map_start(),
 4396: 					$map->map_finish());
 4397: 
 4398:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
 4399: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 4400: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
 4401: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
 4402: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
 4403: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
 4404: 
 4405:     $iterator->next(); # skip the first BEGIN_MAP
 4406:     my $curRes = $iterator->next(); # for "current resource"
 4407:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4408:     while ($depth > 0) {
 4409:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4410:         if($curRes == $iterator->END_MAP) { $depth--; }
 4411: 
 4412:         if (ref($curRes) && $curRes->is_problem()) {
 4413: 	    my $parts = $curRes->parts();
 4414:             my $title = $curRes->compTitle();
 4415: 	    my $symbx = $curRes->symb();
 4416: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
 4417: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
 4418: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4419: 
 4420: 	    my %newrecord=();
 4421: 	    my @displayPts=();
 4422:             my %aggregate = ();
 4423:             my $aggregateflag = 0;
 4424: 	    foreach my $partid (@{$parts}) {
 4425: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4426: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4427: 
 4428: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4429: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4430: 		my $partial = $newpts/$wgt;
 4431: 		my $score;
 4432: 		if ($partial > 0) {
 4433: 		    $score = 'correct_by_override';
 4434: 		} elsif ($newpts ne '') { #empty is taken as 0
 4435: 		    $score = 'incorrect_by_override';
 4436: 		}
 4437: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4438: 		if ($dropMenu eq 'excused') {
 4439: 		    $partial = '';
 4440: 		    $score = 'excused';
 4441: 		} elsif ($dropMenu eq 'reset status'
 4442: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4443: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4444: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4445: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4446: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4447: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4448: 		    $changeflag++;
 4449: 		    $newpts = '';
 4450:                     
 4451:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4452:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4453:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4454:                     if ($aggtries > 0) {
 4455:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4456:                         $aggregateflag = 1;
 4457:                     }
 4458: 		}
 4459: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4460: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4461: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
 4462: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4463: 		    '&nbsp;<br />';
 4464: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
 4465: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4466: 		    '&nbsp;<br />';
 4467: 		$question++;
 4468: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4469: 
 4470: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4471: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4472: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4473: 		    if (scalar(keys(%newrecord)) > 0);
 4474: 
 4475: 		$changeflag++;
 4476: 	    }
 4477: 	    if (scalar(keys(%newrecord)) > 0) {
 4478: 		my %record = 
 4479: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4480: 					     $udom,$uname);
 4481: 
 4482: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4483: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4484: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4485: 		    $newrecord{'resource.CODE'} = '';
 4486: 		}
 4487: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4488: 					$udom,$uname);
 4489: 		%record = &Apache::lonnet::restore($symbx,
 4490: 						   $env{'request.course.id'},
 4491: 						   $udom,$uname);
 4492: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4493: 					     $cdom,$cnum,$udom,$uname);
 4494: 	    }
 4495: 	    
 4496:             if ($aggregateflag) {
 4497:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4498:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4499:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4500:             }
 4501: 
 4502: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4503: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4504: 		'</tr>';
 4505: 
 4506: 	    $prob++;
 4507: 	}
 4508:         $curRes = $iterator->next();
 4509:     }
 4510: 
 4511:     $studentTable.='</td></tr></table></td></tr></table>';
 4512:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4513:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
 4514: 		  'The scores were changed for '.
 4515: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
 4516:     $request->print($grademsg.$studentTable);
 4517: 
 4518:     return '';
 4519: }
 4520: 
 4521: #-------- end of section for handling grading by page/sequence ---------
 4522: #
 4523: #-------------------------------------------------------------------
 4524: 
 4525: #--------------------Scantron Grading-----------------------------------
 4526: #
 4527: #------ start of section for handling grading by page/sequence ---------
 4528: 
 4529: =pod
 4530: 
 4531: =head1 Bubble sheet grading routines
 4532: 
 4533:   For this documentation:
 4534: 
 4535:    'scanline' refers to the full line of characters
 4536:    from the file that we are parsing that represents one entire sheet
 4537: 
 4538:    'bubble line' refers to the data
 4539:    representing the line of bubbles that are on the physical bubble sheet
 4540: 
 4541: 
 4542: The overall process is that a scanned in bubble sheet data is uploaded
 4543: into a course. When a user wants to grade, they select a
 4544: sequence/folder of resources, a file of bubble sheet info, and pick
 4545: one of the predefined configurations for what each scanline looks
 4546: like.
 4547: 
 4548: Next each scanline is checked for any errors of either 'missing
 4549: bubbles' (it's an error because it may have been mis-scanned
 4550: because too light bubbling), 'double bubble' (each bubble line should
 4551: have no more that one letter picked), invalid or duplicated CODE,
 4552: invalid student ID
 4553: 
 4554: If the CODE option is used that determines the randomization of the
 4555: homework problems, either way the student ID is looked up into a
 4556: username:domain.
 4557: 
 4558: During the validation phase the instructor can choose to skip scanlines. 
 4559: 
 4560: After the validation phase, there are now 3 bubble sheet files
 4561: 
 4562:   scantron_original_filename (unmodified original file)
 4563:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4564:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4565: 
 4566: Also there is a separate hash nohist_scantrondata that contains extra
 4567: correction information that isn't representable in the bubble sheet
 4568: file (see &scantron_getfile() for more information)
 4569: 
 4570: After all scanlines are either valid, marked as valid or skipped, then
 4571: foreach line foreach problem in the picked sequence, an ssi request is
 4572: made that simulates a user submitting their selected letter(s) against
 4573: the homework problem.
 4574: 
 4575: =over 4
 4576: 
 4577: 
 4578: 
 4579: =item defaultFormData
 4580: 
 4581:   Returns html hidden inputs used to hold context/default values.
 4582: 
 4583:  Arguments:
 4584:   $symb - $symb of the current resource 
 4585: 
 4586: =cut
 4587: 
 4588: sub defaultFormData {
 4589:     my ($symb)=@_;
 4590:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4591:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4592:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4593: }
 4594: 
 4595: 
 4596: =pod 
 4597: 
 4598: =item getSequenceDropDown
 4599: 
 4600:    Return html dropdown of possible sequences to grade
 4601:  
 4602:  Arguments:
 4603:    $symb - $symb of the current resource 
 4604: 
 4605: =cut
 4606: 
 4607: sub getSequenceDropDown {
 4608:     my ($symb)=@_;
 4609:     my $result='<select name="selectpage">'."\n";
 4610:     my ($titles,$symbx) = &getSymbMap();
 4611:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4612:     my $ctr=0;
 4613:     foreach (@$titles) {
 4614: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4615: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4616: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4617: 	    '>'.$showtitle.'</option>'."\n";
 4618: 	$ctr++;
 4619:     }
 4620:     $result.= '</select>';
 4621:     return $result;
 4622: }
 4623: 
 4624: 
 4625: =pod 
 4626: 
 4627: =item scantron_filenames
 4628: 
 4629:    Returns a list of the scantron files in the current course 
 4630: 
 4631: =cut
 4632: 
 4633: sub scantron_filenames {
 4634:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4635:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4636:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4637: 				    &propath($cdom,$cname));
 4638:     my @possiblenames;
 4639:     foreach my $filename (sort(@files)) {
 4640: 	($filename)=split(/&/,$filename);
 4641: 	if ($filename!~/^scantron_orig_/) { next ; }
 4642: 	$filename=~s/^scantron_orig_//;
 4643: 	push(@possiblenames,$filename);
 4644:     }
 4645:     return @possiblenames;
 4646: }
 4647: 
 4648: =pod 
 4649: 
 4650: =item scantron_uploads
 4651: 
 4652:    Returns  html drop-down list of scantron files in current course.
 4653: 
 4654:  Arguments:
 4655:    $file2grade - filename to set as selected in the dropdown
 4656: 
 4657: =cut
 4658: 
 4659: sub scantron_uploads {
 4660:     my ($file2grade) = @_;
 4661:     my $result=	'<select name="scantron_selectfile">';
 4662:     $result.="<option></option>";
 4663:     foreach my $filename (sort(&scantron_filenames())) {
 4664: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4665:     }
 4666:     $result.="</select>";
 4667:     return $result;
 4668: }
 4669: 
 4670: =pod 
 4671: 
 4672: =item scantron_scantab
 4673: 
 4674:   Returns html drop down of the scantron formats in the scantronformat.tab
 4675:   file.
 4676: 
 4677: =cut
 4678: 
 4679: sub scantron_scantab {
 4680:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4681:     my $result='<select name="scantron_format">'."\n";
 4682:     $result.='<option></option>'."\n";
 4683:     foreach my $line (<$fh>) {
 4684: 	my ($name,$descrip)=split(/:/,$line);
 4685: 	if ($name =~ /^\#/) { next; }
 4686: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4687:     }
 4688:     $result.='</select>'."\n";
 4689: 
 4690:     return $result;
 4691: }
 4692: 
 4693: =pod 
 4694: 
 4695: =item scantron_CODElist
 4696: 
 4697:   Returns html drop down of the saved CODE lists from current course,
 4698:   generated from earlier printings.
 4699: 
 4700: =cut
 4701: 
 4702: sub scantron_CODElist {
 4703:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4704:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4705:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 4706:     my $namechoice='<option></option>';
 4707:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 4708: 	if ($name =~ /^error: 2 /) { next; }
 4709: 	if ($name =~ /^type\0/) { next; }
 4710: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 4711:     }
 4712:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 4713:     return $namechoice;
 4714: }
 4715: 
 4716: =pod 
 4717: 
 4718: =item scantron_CODEunique
 4719: 
 4720:   Returns the html for "Each CODE to be used once" radio.
 4721: 
 4722: =cut
 4723: 
 4724: sub scantron_CODEunique {
 4725:     my $result='<span style="white-space: nowrap;">
 4726:                  <label><input type="radio" name="scantron_CODEunique"
 4727:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 4728:                 </span>
 4729:                 <span style="white-space: nowrap;">
 4730:                  <label><input type="radio" name="scantron_CODEunique"
 4731:                         value="no" />'.&mt('No').' </label>
 4732:                 </span>';
 4733:     return $result;
 4734: }
 4735: 
 4736: =pod 
 4737: 
 4738: =item scantron_selectphase
 4739: 
 4740:   Generates the initial screen to start the bubble sheet process.
 4741:   Allows for - starting a grading run.
 4742:              - downloading existing scan data (original, corrected
 4743:                                                 or skipped info)
 4744: 
 4745:              - uploading new scan data
 4746: 
 4747:  Arguments:
 4748:   $r          - The Apache request object
 4749:   $file2grade - name of the file that contain the scanned data to score
 4750: 
 4751: =cut
 4752: 
 4753: sub scantron_selectphase {
 4754:     my ($r,$file2grade) = @_;
 4755:     my ($symb)=&get_symb($r);
 4756:     if (!$symb) {return '';}
 4757:     my $sequence_selector=&getSequenceDropDown($symb);
 4758:     my $default_form_data=&defaultFormData($symb);
 4759:     my $grading_menu_button=&show_grading_menu_form($symb);
 4760:     my $file_selector=&scantron_uploads($file2grade);
 4761:     my $format_selector=&scantron_scantab();
 4762:     my $CODE_selector=&scantron_CODElist();
 4763:     my $CODE_unique=&scantron_CODEunique();
 4764:     my $result;
 4765: 
 4766:     # Chunk of form to prompt for a file to grade and how:
 4767: 
 4768:     $result.= <<SCANTRONFORM;
 4769:     <table width="100%" border="0">
 4770:     <tr>
 4771:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 4772:       <td bgcolor="#777777">
 4773:        <input type="hidden" name="command" value="scantron_warning" />
 4774:         $default_form_data
 4775:         <table width="100%" border="0">
 4776:           <tr bgcolor="#e6ffff">
 4777:             <td colspan="2">
 4778:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
 4779:             </td>
 4780:           </tr>
 4781:           <tr bgcolor="#ffffe6">
 4782:             <td> Sequence to grade: </td><td> $sequence_selector </td>
 4783:           </tr>
 4784:           <tr bgcolor="#ffffe6">
 4785:             <td> Filename of scoring office file: </td><td> $file_selector </td>
 4786:           </tr>
 4787:           <tr bgcolor="#ffffe6">
 4788:             <td> Format of data file: </td><td> $format_selector </td>
 4789:           </tr>
 4790:           <tr bgcolor="#ffffe6">
 4791:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
 4792:           </tr>
 4793:           <tr bgcolor="#ffffe6">
 4794:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
 4795:           </tr>
 4796:           <tr bgcolor="#ffffe6">
 4797: 	    <td> Options: </td>
 4798:             <td>
 4799: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
 4800:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
 4801:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
 4802: 	    </td>
 4803:           </tr>
 4804:           <tr bgcolor="#ffffe6">
 4805:             <td colspan="2">
 4806:               <input type="submit" value="Grading: Validate Scantron Records" />
 4807:             </td>
 4808:           </tr>
 4809:         </table>
 4810:        </td>
 4811:      </form>
 4812:     </tr>
 4813: SCANTRONFORM
 4814:    
 4815:     $r->print($result);
 4816: 
 4817:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 4818:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 4819: 
 4820: 	# Chunk of form to prompt for a scantron file upload.
 4821: 
 4822:         $r->print(<<SCANTRONFORM);
 4823:     <tr>
 4824:       <td bgcolor="#777777">
 4825:         <table width="100%" border="0">
 4826:           <tr bgcolor="#e6ffff">
 4827:             <td>
 4828:               &nbsp;<b>Specify a Scantron data file to upload.</b>
 4829:             </td>
 4830:           </tr>
 4831:           <tr bgcolor="#ffffe6">
 4832:             <td>
 4833: SCANTRONFORM
 4834:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 4835:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4836:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 4837:     $r->print(<<UPLOAD);
 4838:               <script type="text/javascript" language="javascript">
 4839:     function checkUpload(formname) {
 4840: 	if (formname.upfile.value == "") {
 4841: 	    alert("Please use the browse button to select a file from your local directory.");
 4842: 	    return false;
 4843: 	}
 4844: 	formname.submit();
 4845:     }
 4846:               </script>
 4847: 
 4848:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
 4849:                 $default_form_data
 4850:                 <input name='courseid' type='hidden' value='$cnum' />
 4851:                 <input name='domainid' type='hidden' value='$cdom' />
 4852:                 <input name='command' value='scantronupload_save' type='hidden' />
 4853:                 File to upload:<input type="file" name="upfile" size="50" />
 4854:                 <br />
 4855:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
 4856:               </form>
 4857: UPLOAD
 4858: 
 4859:         $r->print(<<SCANTRONFORM);
 4860:             </td>
 4861:           </tr>
 4862:         </table>
 4863:       </td>
 4864:     </tr>
 4865: SCANTRONFORM
 4866:     }
 4867: 
 4868:     # Chunk of the form that prompts to view a scoring office file,
 4869:     # corrected file, skipped records in a file.
 4870: 
 4871:     $r->print(<<SCANTRONFORM);
 4872:     <tr>
 4873:       <form action='/adm/grades' name='scantron_download'>
 4874:         <td bgcolor="#777777">
 4875: 	  $default_form_data
 4876:           <input type="hidden" name="command" value="scantron_download" />
 4877:           <table width="100%" border="0">
 4878:             <tr bgcolor="#e6ffff">
 4879:               <td colspan="2">
 4880:                 &nbsp;<b>Download a scoring office file</b>
 4881:               </td>
 4882:             </tr>
 4883:             <tr bgcolor="#ffffe6">
 4884:               <td> Filename of scoring office file: </td><td> $file_selector </td>
 4885:             </tr>
 4886:             <tr bgcolor="#ffffe6">
 4887:               <td colspan="2">
 4888:                 <input type="submit" value="Download: Show List of Associated Files" />
 4889:               </td>
 4890:             </tr>
 4891:           </table>
 4892:         </td>
 4893:       </form>
 4894:     </tr>
 4895: SCANTRONFORM
 4896: 
 4897:     $r->print('<tr><td bgcolor="#777777">');
 4898:     &Apache::lonpickcode::code_list($r,2);
 4899:     $r->print('</td></tr></table>');
 4900:     $r->print($grading_menu_button);
 4901:     return
 4902: }
 4903: 
 4904: =pod
 4905: 
 4906: =item get_scantron_config
 4907: 
 4908:    Parse and return the scantron configuration line selected as a
 4909:    hash of configuration file fields.
 4910: 
 4911:  Arguments:
 4912:     which - the name of the configuration to parse from the file.
 4913: 
 4914: 
 4915:  Returns:
 4916:             If the named configuration is not in the file, an empty
 4917:             hash is returned.
 4918:     a hash with the fields
 4919:       name         - internal name for the this configuration setup
 4920:       description  - text to display to operator that describes this config
 4921:       CODElocation - if 0 or the string 'none'
 4922:                           - no CODE exists for this config
 4923:                      if -1 || the string 'letter'
 4924:                           - a CODE exists for this config and is
 4925:                             a string of letters
 4926:                      Unsupported value (but planned for future support)
 4927:                           if a positive integer
 4928:                                - The CODE exists as the first n items from
 4929:                                  the question section of the form
 4930:                           if the string 'number'
 4931:                                - The CODE exists for this config and is
 4932:                                  a string of numbers
 4933:       CODEstart   - (only matter if a CODE exists) column in the line where
 4934:                      the CODE starts
 4935:       CODElength  - length of the CODE
 4936:       IDstart     - column where the student ID number starts
 4937:       IDlength    - length of the student ID info
 4938:       Qstart      - column where the information from the bubbled
 4939:                     'questions' start
 4940:       Qlength     - number of columns comprising a single bubble line from
 4941:                     the sheet. (usually either 1 or 10)
 4942:       Qon         - either a single character representing the character used
 4943:                     to signal a bubble was chosen in the positional setup, or
 4944:                     the string 'letter' if the letter of the chosen bubble is
 4945:                     in the final, or 'number' if a number representing the
 4946:                     chosen bubble is in the file (1->A 0->J)
 4947:       Qoff        - the character used to represent that a bubble was
 4948:                     left blank
 4949:       PaperID     - if the scanning process generates a unique number for each
 4950:                     sheet scanned the column that this ID number starts in
 4951:       PaperIDlength - number of columns that comprise the unique ID number
 4952:                       for the sheet of paper
 4953:       FirstName   - column that the first name starts in
 4954:       FirstNameLength - number of columns that the first name spans
 4955:  
 4956:       LastName    - column that the last name starts in
 4957:       LastNameLength - number of columns that the last name spans
 4958: 
 4959: =cut
 4960: 
 4961: sub get_scantron_config {
 4962:     my ($which) = @_;
 4963:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4964:     my %config;
 4965:     #FIXME probably should move to XML it has already gotten a bit much now
 4966:     foreach my $line (<$fh>) {
 4967: 	my ($name,$descrip)=split(/:/,$line);
 4968: 	if ($name ne $which ) { next; }
 4969: 	chomp($line);
 4970: 	my @config=split(/:/,$line);
 4971: 	$config{'name'}=$config[0];
 4972: 	$config{'description'}=$config[1];
 4973: 	$config{'CODElocation'}=$config[2];
 4974: 	$config{'CODEstart'}=$config[3];
 4975: 	$config{'CODElength'}=$config[4];
 4976: 	$config{'IDstart'}=$config[5];
 4977: 	$config{'IDlength'}=$config[6];
 4978: 	$config{'Qstart'}=$config[7];
 4979: 	$config{'Qlength'}=$config[8];
 4980: 	$config{'Qoff'}=$config[9];
 4981: 	$config{'Qon'}=$config[10];
 4982: 	$config{'PaperID'}=$config[11];
 4983: 	$config{'PaperIDlength'}=$config[12];
 4984: 	$config{'FirstName'}=$config[13];
 4985: 	$config{'FirstNamelength'}=$config[14];
 4986: 	$config{'LastName'}=$config[15];
 4987: 	$config{'LastNamelength'}=$config[16];
 4988: 	last;
 4989:     }
 4990:     return %config;
 4991: }
 4992: 
 4993: =pod 
 4994: 
 4995: =item username_to_idmap
 4996: 
 4997:     creates a hash keyed by student id with values of the corresponding
 4998:     student username:domain.
 4999: 
 5000:   Arguments:
 5001: 
 5002:     $classlist - reference to the class list hash. This is a hash
 5003:                  keyed by student name:domain  whose elements are references
 5004:                  to arrays containing various chunks of information
 5005:                  about the student. (See loncoursedata for more info).
 5006: 
 5007:   Returns
 5008:     %idmap - the constructed hash
 5009: 
 5010: =cut
 5011: 
 5012: sub username_to_idmap {
 5013:     my ($classlist)= @_;
 5014:     my %idmap;
 5015:     foreach my $student (keys(%$classlist)) {
 5016: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 5017: 	    $student;
 5018:     }
 5019:     return %idmap;
 5020: }
 5021: 
 5022: =pod
 5023: 
 5024: =item scantron_fixup_scanline
 5025: 
 5026:    Process a requested correction to a scanline.
 5027: 
 5028:   Arguments:
 5029:     $scantron_config   - hash from &get_scantron_config()
 5030:     $scan_data         - hash of correction information 
 5031:                           (see &scantron_getfile())
 5032:     $line              - existing scanline
 5033:     $whichline         - line number of the passed in scanline
 5034:     $field             - type of change to process 
 5035:                          (either 
 5036:                           'ID'     -> correct the student ID number
 5037:                           'CODE'   -> correct the CODE
 5038:                           'answer' -> fixup the submitted answers)
 5039:     
 5040:    $args               - hash of additional info,
 5041:                           - 'ID' 
 5042:                                'newid' -> studentID to use in replacement
 5043:                                           of existing one
 5044:                           - 'CODE' 
 5045:                                'CODE_ignore_dup' - set to true if duplicates
 5046:                                                    should be ignored.
 5047: 	                       'CODE' - is new code or 'use_unfound'
 5048:                                         if the existing unfound code should
 5049:                                         be used as is
 5050:                           - 'answer'
 5051:                                'response' - new answer or 'none' if blank
 5052:                                'question' - the bubble line to change
 5053: 
 5054:   Returns:
 5055:     $line - the modified scanline
 5056: 
 5057:   Side effects: 
 5058:     $scan_data - may be updated
 5059: 
 5060: =cut
 5061: 
 5062: 
 5063: sub scantron_fixup_scanline {
 5064:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5065: 
 5066:     if ($field eq 'ID') {
 5067: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5068: 	    return ($line,1,'New value too large');
 5069: 	}
 5070: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5071: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5072: 				     $args->{'newid'});
 5073: 	}
 5074: 	substr($line,$$scantron_config{'IDstart'}-1,
 5075: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5076: 	if ($args->{'newid'}=~/^\s*$/) {
 5077: 	    &scan_data($scan_data,"$whichline.user",
 5078: 		       $args->{'username'}.':'.$args->{'domain'});
 5079: 	}
 5080:     } elsif ($field eq 'CODE') {
 5081: 	if ($args->{'CODE_ignore_dup'}) {
 5082: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5083: 	}
 5084: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5085: 	if ($args->{'CODE'} ne 'use_unfound') {
 5086: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5087: 		return ($line,1,'New CODE value too large');
 5088: 	    }
 5089: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5090: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5091: 	    }
 5092: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5093: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5094: 	}
 5095:     } elsif ($field eq 'answer') {
 5096: 	my $length=$scantron_config->{'Qlength'};
 5097: 	my $off=$scantron_config->{'Qoff'};
 5098: 	my $on=$scantron_config->{'Qon'};
 5099: 	my $answer=${off}x$length;
 5100: 	if ($args->{'response'} eq 'none') {
 5101: 	    &scan_data($scan_data,
 5102: 		       "$whichline.no_bubble.".$args->{'question'},'1');
 5103: 	} else {
 5104: 	    if ($on eq 'letter') {
 5105: 		my @alphabet=('A'..'Z');
 5106: 		$answer=$alphabet[$args->{'response'}];
 5107: 	    } elsif ($on eq 'number') {
 5108: 		$answer=$args->{'response'}+1;
 5109: 		if ($answer == 10) { $answer = '0'; }
 5110: 	    } else {
 5111: 		substr($answer,$args->{'response'},1)=$on;
 5112: 	    }
 5113: 	    &scan_data($scan_data,
 5114: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
 5115: 	}
 5116: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5117: 	substr($line,$where-1,$length)=$answer;
 5118:     }
 5119:     return $line;
 5120: }
 5121: 
 5122: =pod
 5123: 
 5124: =item scan_data
 5125: 
 5126:     Edit or look up  an item in the scan_data hash.
 5127: 
 5128:   Arguments:
 5129:     $scan_data  - The hash (see scantron_getfile)
 5130:     $key        - shorthand of the key to edit (actual key is
 5131:                   scantronfilename_key).
 5132:     $data        - New value of the hash entry.
 5133:     $delete      - If true, the entry is removed from the hash.
 5134: 
 5135:   Returns:
 5136:     The new value of the hash table field (undefined if deleted).
 5137: 
 5138: =cut
 5139: 
 5140: 
 5141: sub scan_data {
 5142:     my ($scan_data,$key,$value,$delete)=@_;
 5143:     my $filename=$env{'form.scantron_selectfile'};
 5144:     if (defined($value)) {
 5145: 	$scan_data->{$filename.'_'.$key} = $value;
 5146:     }
 5147:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5148:     return $scan_data->{$filename.'_'.$key};
 5149: }
 5150: 
 5151: =pod 
 5152: 
 5153: =item scantron_parse_scanline
 5154: 
 5155:   Decodes a scanline from the selected scantron file
 5156: 
 5157:  Arguments:
 5158:     line             - The text of the scantron file line to process
 5159:     whichline        - Line number
 5160:     scantron_config  - Hash describing the format of the scantron lines.
 5161:     scan_data        - Hash of extra information about the scanline
 5162:                        (see scantron_getfile for more information)
 5163:     just_header      - True if should not process question answers but only
 5164:                        the stuff to the left of the answers.
 5165:  Returns:
 5166:    Hash containing the result of parsing the scanline
 5167: 
 5168:    Keys are all proceeded by the string 'scantron.'
 5169: 
 5170:        CODE    - the CODE in use for this scanline
 5171:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5172:                  by the operator
 5173:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5174:                             CODEs were selected, but the usage has been
 5175:                             forced by the operator
 5176:        ID  - student ID
 5177:        PaperID - if used, the ID number printed on the sheet when the 
 5178:                  paper was scanned
 5179:        FirstName - first name from the sheet
 5180:        LastName  - last name from the sheet
 5181: 
 5182:      if just_header was not true these key may also exist
 5183: 
 5184:        missingerror - a list of bubble ranges that are considered to be answers
 5185:                       to a single question that don't have any bubbles filled in.
 5186:                       Of the form questionnumber:firstbubblenumber:count.
 5187:        doubleerror  - a list of bubble ranges that are considered to be answers
 5188:                       to a single question that have more than one bubble filled in.
 5189:                       Of the form questionnumber::firstbubblenumber:count
 5190:    
 5191:                 In the above, count is the number of bubble responses in the
 5192:                 input line needed to represent the possible answers to the question.
 5193:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5194:                 per line would have count = 2.
 5195: 
 5196:        maxquest     - the number of the last bubble line that was parsed
 5197: 
 5198:        (<number> starts at 1)
 5199:        <number>.answer - zero or more letters representing the selected
 5200:                          letters from the scanline for the bubble line 
 5201:                          <number>.
 5202:                          if blank there was either no bubble or there where
 5203:                          multiple bubbles, (consult the keys missingerror and
 5204:                          doubleerror if this is an error condition)
 5205: 
 5206: =cut
 5207: 
 5208: sub scantron_parse_scanline {
 5209:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5210:     my %record;
 5211:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
 5212:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5213:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5214: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5215: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5216: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5217: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5218: 	    $record{'scantron.CODE'}=substr($data,
 5219: 					    $$scantron_config{'CODEstart'}-1,
 5220: 					    $$scantron_config{'CODElength'});
 5221: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5222: 		$record{'scantron.useCODE'}=1;
 5223: 	    }
 5224: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5225: 		$record{'scantron.CODE_ignore_dup'}=1;
 5226: 	    }
 5227: 	} else {
 5228: 	    #FIXME interpret first N questions
 5229: 	}
 5230:     }
 5231:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5232: 				  $$scantron_config{'IDlength'});
 5233:     $record{'scantron.PaperID'}=
 5234: 	substr($data,$$scantron_config{'PaperID'}-1,
 5235: 	       $$scantron_config{'PaperIDlength'});
 5236:     $record{'scantron.FirstName'}=
 5237: 	substr($data,$$scantron_config{'FirstName'}-1,
 5238: 	       $$scantron_config{'FirstNamelength'});
 5239:     $record{'scantron.LastName'}=
 5240: 	substr($data,$$scantron_config{'LastName'}-1,
 5241: 	       $$scantron_config{'LastNamelength'});
 5242:     if ($just_header) { return \%record; }
 5243: 
 5244:     my @alphabet=('A'..'Z');
 5245:     my $questnum=0;
 5246:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5247: 
 5248:     while ($questions) {
 5249: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5250: 	my $answer_length  = $$scantron_config{'Qlength'} * $answers_needed;
 5251: 
 5252: 
 5253: 
 5254: 	$questnum++;
 5255: 	my $currentquest = substr($questions,0,$answer_length);
 5256: 	$questions       = substr($questions,0,$answer_length)='';
 5257: 	if (length($currentquest) < $answer_length) { next; }
 5258: 
 5259: 	# Qon letter implies for each slot in currentquest we have:
 5260: 	#    ? or * for doubles a letter in A-Z for a bubble and
 5261:         #    about anything else (esp. a value of Qoff for missing
 5262: 	#    bubbles.
 5263: 
 5264: 
 5265: 	if ($$scantron_config{'Qon'} eq 'letter') {
 5266: 
 5267: 	    if ($currentquest =~ /\?/
 5268: 		|| $currentquest =~ /\*/
 5269: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
 5270: 		push(@{$record{'scantron.doubleerror'}},$questnum);
 5271: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
 5272: 		    my $bubble = substr($currentquest, $ans, 1);
 5273: 		    if ($bubble =~ /[A-Z]/ ) {
 5274: 			$record{"scantron.$ansnum.answer"} = $bubble;
 5275: 		    } else {
 5276: 			$record{"scantron.$ansnum.answer"}='';
 5277: 		    }
 5278: 		    $ansnum++;
 5279: 		}
 5280: 
 5281: 	    } elsif (!defined($currentquest)
 5282: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
 5283: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
 5284: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
 5285: 		    $record{"scantron.$ansnum.answer"}='';
 5286: 		    $ansnum++;
 5287: 
 5288: 		}
 5289: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
 5290: 		    push(@{$record{"scantron.missingerror"}},$questnum);
 5291: 		    $ansnum += $answers_needed;
 5292: 		}
 5293: 
 5294: 	    } else {
 5295: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
 5296: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
 5297: 		    $ansnum++;
 5298: 		}
 5299: 	    }
 5300: 
 5301: 	# Qon 'number' implies each slot gives a digit that indexes the
 5302: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
 5303:         #    and *? for double bubbles on a line.
 5304: 	#    these answers are also stored as letters.
 5305: 
 5306: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
 5307: 	    if ($currentquest =~ /\?/
 5308: 		|| $currentquest =~ /\*/
 5309: 		|| (&occurence_count($currentquest, '\d') > 1)) {
 5310: 		push(@{$record{'scantron.doubleerror'}},$questnum);
 5311: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
 5312: 		    my $bubble = substr($currentquest, $ans, 1);
 5313: 		    if ($bubble =~ /\d/) {
 5314: 			$record{"scantron.$ansnum.answer"} = $alphabet[$bubble];
 5315: 		    } else {
 5316: 			$record{"scantron.$ansnum.answer"}=' ';
 5317: 		    }
 5318: 		    $ansnum++;
 5319: 		}
 5320: 
 5321: 	    } elsif (!defined($currentquest)
 5322: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
 5323: 		     || (&occurence_count($currentquest, '\d') == 0)) {
 5324: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
 5325: 		    $record{"scantron.$ansnum.answer"}='';
 5326: 		    $ansnum++;
 5327: 
 5328: 		}
 5329: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
 5330: 		    push(@{$record{"scantron.missingerror"}},$questnum);
 5331: 		    $ansnum += $answers_needed;
 5332: 		}
 5333: 
 5334: 	    } else {
 5335: 		$currentquest = &digits_to_letters($currentquest);
 5336: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
 5337: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
 5338: 		    $ansnum++;
 5339: 		}
 5340: 	    }
 5341: 	} else {
 5342: 
 5343: 	    # Otherwise there's a positional notation;
 5344: 	    # each bubble line requires Qlength items, and there are filled in
 5345: 	    # bubbles for each case where there 'Qon' characters.
 5346: 	    #
 5347: 
 5348: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
 5349: 
 5350: 	    # If the split only  giveas us one element.. the full length of the
 5351: 	    # answser string, no bubbles are filled in:
 5352: 
 5353: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5354: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
 5355: 		    $record{"scantron.$ansnum.answer"}='';
 5356: 		    $ansnum++;
 5357: 
 5358: 		}
 5359: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
 5360: 		    push(@{$record{"scantron.missingerror"}},$questnum);
 5361: 		}
 5362: 	    } elsif (scalar(@array) lt 2) {
 5363: 
 5364: 		my $location      = length($array[0]);
 5365: 		my $line_num      = $location / $$scantron_config{'Qlength'};
 5366: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
 5367: 
 5368: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
 5369: 		    if ($ans eq $line_num) {
 5370: 			$record{"scantron.$ansnum.answer"} = $bubble;
 5371: 		    } else {
 5372: 			$record{"scantron.$ansnum.answer"} = ' ';
 5373: 		    }
 5374: 		    $ansnum++;
 5375: 		}
 5376: 	    }
 5377: 	    #  If there's more than one instance of a bubble character
 5378: 	    #  That's a double bubble; with positional notation we can
 5379: 	    #  record all the bubbles filled in as well as the 
 5380: 	    #  fact this response consists of multiple bubbles.
 5381: 	    #
 5382: 	    else {
 5383: 		push(@{$record{'scantron.doubleerror'}},$questnum);
 5384: 
 5385: 		my $first_answer = $ansnum;
 5386: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
 5387: 		    my $item = $first_answer+$ans;
 5388: 		    $record{"scantron.$item.answer"} = '';
 5389: 		}
 5390: 
 5391: 		my @ans=@array;
 5392: 		my $i=0;
 5393: 		my $increment = 0;
 5394: 		while ($#ans) {
 5395: 		    $i+=length($ans[0]) + $increment;
 5396: 		    my $line   = int($i/$$scantron_config{'Qlength'} + $first_answer);
 5397: 		    my $bubble = $i%$$scantron_config{'Qlength'};
 5398: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
 5399: 		    shift(@ans);
 5400: 		    $increment = 1;
 5401: 		}
 5402: 		$ansnum += $answers_needed;
 5403: 	    }
 5404: 	}
 5405:     }
 5406:     $record{'scantron.maxquest'}=$questnum;
 5407:     return \%record;
 5408: }
 5409: 
 5410: =pod
 5411: 
 5412: =item scantron_add_delay
 5413: 
 5414:    Adds an error message that occurred during the grading phase to a
 5415:    queue of messages to be shown after grading pass is complete
 5416: 
 5417:  Arguments:
 5418:    $delayqueue  - arrary ref of hash ref of error messages
 5419:    $scanline    - the scanline that caused the error
 5420:    $errormesage - the error message
 5421:    $errorcode   - a numeric code for the error
 5422: 
 5423:  Side Effects:
 5424:    updates the $delayqueue to have a new hash ref of the error
 5425: 
 5426: =cut
 5427: 
 5428: sub scantron_add_delay {
 5429:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5430:     push(@$delayqueue,
 5431: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5432: 	  'ecode' => $errorcode }
 5433: 	 );
 5434: }
 5435: 
 5436: =pod
 5437: 
 5438: =item scantron_find_student
 5439: 
 5440:    Finds the username for the current scanline
 5441: 
 5442:   Arguments:
 5443:    $scantron_record - hash result from scantron_parse_scanline
 5444:    $scan_data       - hash of correction information 
 5445:                       (see &scantron_getfile() form more information)
 5446:    $idmap           - hash from &username_to_idmap()
 5447:    $line            - number of current scanline
 5448:  
 5449:   Returns:
 5450:    Either 'username:domain' or undef if unknown
 5451: 
 5452: =cut
 5453: 
 5454: sub scantron_find_student {
 5455:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5456:     my $scanID=$$scantron_record{'scantron.ID'};
 5457:     if ($scanID =~ /^\s*$/) {
 5458:  	return &scan_data($scan_data,"$line.user");
 5459:     }
 5460:     foreach my $id (keys(%$idmap)) {
 5461:  	if (lc($id) eq lc($scanID)) {
 5462:  	    return $$idmap{$id};
 5463:  	}
 5464:     }
 5465:     return undef;
 5466: }
 5467: 
 5468: =pod
 5469: 
 5470: =item scantron_filter
 5471: 
 5472:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5473:    hidden resources was selected
 5474: 
 5475: =cut
 5476: 
 5477: sub scantron_filter {
 5478:     my ($curres)=@_;
 5479: 
 5480:     if (ref($curres) && $curres->is_problem()) {
 5481: 	# if the user has asked to not have either hidden
 5482: 	# or 'randomout' controlled resources to be graded
 5483: 	# don't include them
 5484: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5485: 	    && $curres->randomout) {
 5486: 	    return 0;
 5487: 	}
 5488: 	return 1;
 5489:     }
 5490:     return 0;
 5491: }
 5492: 
 5493: =pod
 5494: 
 5495: =item scantron_process_corrections
 5496: 
 5497:    Gets correction information out of submitted form data and corrects
 5498:    the scanline
 5499: 
 5500: =cut
 5501: 
 5502: sub scantron_process_corrections {
 5503:     my ($r) = @_;
 5504:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5505:     my ($scanlines,$scan_data)=&scantron_getfile();
 5506:     my $classlist=&Apache::loncoursedata::get_classlist();
 5507:     my $which=$env{'form.scantron_line'};
 5508:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5509:     my ($skip,$err,$errmsg);
 5510:     if ($env{'form.scantron_skip_record'}) {
 5511: 	$skip=1;
 5512:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5513: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5514: 	    $env{'form.scantron_domain'};
 5515: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5516: 	($line,$err,$errmsg)=
 5517: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5518: 				     'ID',{'newid'=>$newid,
 5519: 				    'username'=>$env{'form.scantron_username'},
 5520: 				    'domain'=>$env{'form.scantron_domain'}});
 5521:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5522: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5523: 	my $newCODE;
 5524: 	my %args;
 5525: 	if      ($resolution eq 'use_unfound') {
 5526: 	    $newCODE='use_unfound';
 5527: 	} elsif ($resolution eq 'use_found') {
 5528: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5529: 	} elsif ($resolution eq 'use_typed') {
 5530: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5531: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5532: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5533: 	}
 5534: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5535: 	    $args{'CODE_ignore_dup'}=1;
 5536: 	}
 5537: 	$args{'CODE'}=$newCODE;
 5538: 	($line,$err,$errmsg)=
 5539: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5540: 				     'CODE',\%args);
 5541:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5542: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5543: 	    ($line,$err,$errmsg)=
 5544: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5545: 					 $which,'answer',
 5546: 					 { 'question'=>$question,
 5547: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
 5548: 	    if ($err) { last; }
 5549: 	}
 5550:     }
 5551:     if ($err) {
 5552: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5553:     } else {
 5554: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5555: 	&scantron_putfile($scanlines,$scan_data);
 5556:     }
 5557: }
 5558: 
 5559: =pod
 5560: 
 5561: =item reset_skipping_status
 5562: 
 5563:    Forgets the current set of remember skipped scanlines (and thus
 5564:    reverts back to considering all lines in the
 5565:    scantron_skipped_<filename> file)
 5566: 
 5567: =cut
 5568: 
 5569: sub reset_skipping_status {
 5570:     my ($scanlines,$scan_data)=&scantron_getfile();
 5571:     &scan_data($scan_data,'remember_skipping',undef,1);
 5572:     &scantron_putfile(undef,$scan_data);
 5573: }
 5574: 
 5575: =pod
 5576: 
 5577: =item start_skipping
 5578: 
 5579:    Marks a scanline to be skipped. 
 5580: 
 5581: =cut
 5582: 
 5583: sub start_skipping {
 5584:     my ($scan_data,$i)=@_;
 5585:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5586:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 5587: 	$remembered{$i}=2;
 5588:     } else {
 5589: 	$remembered{$i}=1;
 5590:     }
 5591:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 5592: }
 5593: 
 5594: =pod
 5595: 
 5596: =item should_be_skipped
 5597: 
 5598:    Checks whether a scanline should be skipped.
 5599: 
 5600: =cut
 5601: 
 5602: sub should_be_skipped {
 5603:     my ($scanlines,$scan_data,$i)=@_;
 5604:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 5605: 	# not redoing old skips
 5606: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 5607: 	return 0;
 5608:     }
 5609:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5610: 
 5611:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 5612: 	return 0;
 5613:     }
 5614:     return 1;
 5615: }
 5616: 
 5617: =pod
 5618: 
 5619: =item remember_current_skipped
 5620: 
 5621:    Discovers what scanlines are in the scantron_skipped_<filename>
 5622:    file and remembers them into scan_data for later use.
 5623: 
 5624: =cut
 5625: 
 5626: sub remember_current_skipped {
 5627:     my ($scanlines,$scan_data)=&scantron_getfile();
 5628:     my %to_remember;
 5629:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 5630: 	if ($scanlines->{'skipped'}[$i]) {
 5631: 	    $to_remember{$i}=1;
 5632: 	}
 5633:     }
 5634: 
 5635:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 5636:     &scantron_putfile(undef,$scan_data);
 5637: }
 5638: 
 5639: =pod
 5640: 
 5641: =item check_for_error
 5642: 
 5643:     Checks if there was an error when attempting to remove a specific
 5644:     scantron_.. bubble sheet data file. Prints out an error if
 5645:     something went wrong.
 5646: 
 5647: =cut
 5648: 
 5649: sub check_for_error {
 5650:     my ($r,$result)=@_;
 5651:     if ($result ne 'ok' && $result ne 'not_found' ) {
 5652: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
 5653:     }
 5654: }
 5655: 
 5656: =pod
 5657: 
 5658: =item scantron_warning_screen
 5659: 
 5660:    Interstitial screen to make sure the operator has selected the
 5661:    correct options before we start the validation phase.
 5662: 
 5663: =cut
 5664: 
 5665: sub scantron_warning_screen {
 5666:     my ($button_text)=@_;
 5667:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 5668:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5669:     my $CODElist;
 5670:     if ($scantron_config{'CODElocation'} &&
 5671: 	$scantron_config{'CODEstart'} &&
 5672: 	$scantron_config{'CODElength'}) {
 5673: 	$CODElist=$env{'form.scantron_CODElist'};
 5674: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 5675: 	$CODElist=
 5676: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
 5677: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 5678:     }
 5679:     return (<<STUFF);
 5680: <p>
 5681: <span class="LC_warning">Please double check the information
 5682:                  below before clicking on '$button_text'</span>
 5683: </p>
 5684: <table>
 5685: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
 5686: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
 5687: $CODElist
 5688: </table>
 5689: <br />
 5690: <p> If this information is correct, please click on '$button_text'.</p>
 5691: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
 5692: 
 5693: <br />
 5694: STUFF
 5695: }
 5696: 
 5697: =pod
 5698: 
 5699: =item scantron_do_warning
 5700: 
 5701:    Check if the operator has picked something for all required
 5702:    fields. Error out if something is missing.
 5703: 
 5704: =cut
 5705: 
 5706: sub scantron_do_warning {
 5707:     my ($r)=@_;
 5708:     my ($symb)=&get_symb($r);
 5709:     if (!$symb) {return '';}
 5710:     my $default_form_data=&defaultFormData($symb);
 5711:     $r->print(&scantron_form_start().$default_form_data);
 5712:     if ( $env{'form.selectpage'} eq '' ||
 5713: 	 $env{'form.scantron_selectfile'} eq '' ||
 5714: 	 $env{'form.scantron_format'} eq '' ) {
 5715: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
 5716: 	if ( $env{'form.selectpage'} eq '') {
 5717: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
 5718: 	} 
 5719: 	if ( $env{'form.scantron_selectfile'} eq '') {
 5720: 	    $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
 5721: 	} 
 5722: 	if ( $env{'form.scantron_format'} eq '') {
 5723: 	    $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
 5724: 	} 
 5725:     } else {
 5726: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 5727: 	$r->print(<<STUFF);
 5728: $warning
 5729: <input type="submit" name="submit" value="Grading: Validate Records" />
 5730: <input type="hidden" name="command" value="scantron_validate" />
 5731: STUFF
 5732:     }
 5733:     $r->print("</form><br />".&show_grading_menu_form($symb));
 5734:     return '';
 5735: }
 5736: 
 5737: =pod
 5738: 
 5739: =item scantron_form_start
 5740: 
 5741:     html hidden input for remembering all selected grading options
 5742: 
 5743: =cut
 5744: 
 5745: sub scantron_form_start {
 5746:     my ($max_bubble)=@_;
 5747:     my $result= <<SCANTRONFORM;
 5748: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 5749:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 5750:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 5751:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 5752:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 5753:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 5754:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 5755:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 5756:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 5757:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 5758: SCANTRONFORM
 5759: 
 5760:   my $line = 0;
 5761:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 5762:        my $chunk =
 5763: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 5764:        $chunk .=
 5765: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 5766:        $result .= $chunk;
 5767:        $line++;
 5768:    }
 5769:     return $result;
 5770: }
 5771: 
 5772: =pod
 5773: 
 5774: =item scantron_validate_file
 5775: 
 5776:     Dispatch routine for doing validation of a bubble sheet data file.
 5777: 
 5778:     Also processes any necessary information resets that need to
 5779:     occur before validation begins (ignore previous corrections,
 5780:     restarting the skipped records processing)
 5781: 
 5782: =cut
 5783: 
 5784: sub scantron_validate_file {
 5785:     my ($r) = @_;
 5786:     my ($symb)=&get_symb($r);
 5787:     if (!$symb) {return '';}
 5788:     my $default_form_data=&defaultFormData($symb);
 5789:     
 5790:     # do the detection of only doing skipped records first befroe we delete
 5791:     # them when doing the corrections reset
 5792:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 5793: 	&reset_skipping_status();
 5794:     }
 5795:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 5796: 	&remember_current_skipped();
 5797: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 5798:     }
 5799: 
 5800:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 5801: 	&check_for_error($r,&scantron_remove_file('corrected'));
 5802: 	&check_for_error($r,&scantron_remove_file('skipped'));
 5803: 	&check_for_error($r,&scantron_remove_scan_data());
 5804: 	$env{'form.scantron_options_ignore'}='done';
 5805:     }
 5806: 
 5807:     if ($env{'form.scantron_corrections'}) {
 5808: 	&scantron_process_corrections($r);
 5809:     }
 5810:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
 5811:     #get the student pick code ready
 5812:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 5813:     my $max_bubble=&scantron_get_maxbubble();
 5814:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 5815:     $r->print($result);
 5816:     
 5817:     my @validate_phases=( 'sequence',
 5818: 			  'ID',
 5819: 			  'CODE',
 5820: 			  'doublebubble',
 5821: 			  'missingbubbles');
 5822:     if (!$env{'form.validatepass'}) {
 5823: 	$env{'form.validatepass'} = 0;
 5824:     }
 5825:     my $currentphase=$env{'form.validatepass'};
 5826: 
 5827: 
 5828:     my $stop=0;
 5829:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 5830: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
 5831: 	$r->rflush();
 5832: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 5833: 	{
 5834: 	    no strict 'refs';
 5835: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 5836: 	}
 5837:     }
 5838:     if (!$stop) {
 5839: 	my $warning=&scantron_warning_screen('Start Grading');
 5840: 	$r->print(<<STUFF);
 5841: Validation process complete.<br />
 5842: $warning
 5843: <input type="submit" name="submit" value="Start Grading" />
 5844: <input type="hidden" name="command" value="scantron_process" />
 5845: STUFF
 5846: 
 5847:     } else {
 5848: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 5849: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 5850:     }
 5851:     if ($stop) {
 5852: 	if ($validate_phases[$currentphase] eq 'sequence') {
 5853: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
 5854: 	    $r->print(' this error <br />');
 5855: 
 5856: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
 5857: 	} else {
 5858: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
 5859: 	    $r->print(' using corrected info <br />');
 5860: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
 5861: 	    $r->print(" this scanline saving it for later.");
 5862: 	}
 5863:     }
 5864:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 5865:     return '';
 5866: }
 5867: 
 5868: 
 5869: =pod
 5870: 
 5871: =item scantron_remove_file
 5872: 
 5873:    Removes the requested bubble sheet data file, makes sure that
 5874:    scantron_original_<filename> is never removed
 5875: 
 5876: 
 5877: =cut
 5878: 
 5879: sub scantron_remove_file {
 5880:     my ($which)=@_;
 5881:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5882:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5883:     my $file='scantron_';
 5884:     if ($which eq 'corrected' || $which eq 'skipped') {
 5885: 	$file.=$which.'_';
 5886:     } else {
 5887: 	return 'refused';
 5888:     }
 5889:     $file.=$env{'form.scantron_selectfile'};
 5890:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 5891: }
 5892: 
 5893: 
 5894: =pod
 5895: 
 5896: =item scantron_remove_scan_data
 5897: 
 5898:    Removes all scan_data correction for the requested bubble sheet
 5899:    data file.  (In the case that both the are doing skipped records we need
 5900:    to remember the old skipped lines for the time being so that element
 5901:    persists for a while.)
 5902: 
 5903: =cut
 5904: 
 5905: sub scantron_remove_scan_data {
 5906:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5907:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5908:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 5909:     my @todelete;
 5910:     my $filename=$env{'form.scantron_selectfile'};
 5911:     foreach my $key (@keys) {
 5912: 	if ($key=~/^\Q$filename\E_/) {
 5913: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 5914: 		$key=~/remember_skipping/) {
 5915: 		next;
 5916: 	    }
 5917: 	    push(@todelete,$key);
 5918: 	}
 5919:     }
 5920:     my $result;
 5921:     if (@todelete) {
 5922: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
 5923:     }
 5924:     return $result;
 5925: }
 5926: 
 5927: 
 5928: =pod
 5929: 
 5930: =item scantron_getfile
 5931: 
 5932:     Fetches the requested bubble sheet data file (all 3 versions), and
 5933:     the scan_data hash
 5934:   
 5935:   Arguments:
 5936:     None
 5937: 
 5938:   Returns:
 5939:     2 hash references
 5940: 
 5941:      - first one has 
 5942:          orig      -
 5943:          corrected -
 5944:          skipped   -  each of which points to an array ref of the specified
 5945:                       file broken up into individual lines
 5946:          count     - number of scanlines
 5947:  
 5948:      - second is the scan_data hash possible keys are
 5949:        ($number refers to scanline numbered $number and thus the key affects
 5950:         only that scanline
 5951:         $bubline refers to the specific bubble line element and the aspects
 5952:         refers to that specific bubble line element)
 5953: 
 5954:        $number.user - username:domain to use
 5955:        $number.CODE_ignore_dup 
 5956:                     - ignore the duplicate CODE error 
 5957:        $number.useCODE
 5958:                     - use the CODE in the scanline as is
 5959:        $number.no_bubble.$bubline
 5960:                     - it is valid that there is no bubbled in bubble
 5961:                       at $number $bubline
 5962:        remember_skipping
 5963:                     - a frozen hash containing keys of $number and values
 5964:                       of either 
 5965:                         1 - we are on a 'do skipped records pass' and plan
 5966:                             on processing this line
 5967:                         2 - we are on a 'do skipped records pass' and this
 5968:                             scanline has been marked to skip yet again
 5969: 
 5970: =cut
 5971: 
 5972: sub scantron_getfile {
 5973:     #FIXME really would prefer a scantron directory
 5974:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5975:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5976:     my $lines;
 5977:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 5978: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 5979:     my %scanlines;
 5980:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 5981:     my $temp=$scanlines{'orig'};
 5982:     $scanlines{'count'}=$#$temp;
 5983: 
 5984:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 5985: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 5986:     if ($lines eq '-1') {
 5987: 	$scanlines{'corrected'}=[];
 5988:     } else {
 5989: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 5990:     }
 5991:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 5992: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 5993:     if ($lines eq '-1') {
 5994: 	$scanlines{'skipped'}=[];
 5995:     } else {
 5996: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 5997:     }
 5998:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 5999:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 6000:     my %scan_data = @tmp;
 6001:     return (\%scanlines,\%scan_data);
 6002: }
 6003: 
 6004: =pod
 6005: 
 6006: =item lonnet_putfile
 6007: 
 6008:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 6009: 
 6010:  Arguments:
 6011:    $contents - data to store
 6012:    $filename - filename to store $contents into
 6013: 
 6014:  Returns:
 6015:    result value from &Apache::lonnet::finishuserfileupload
 6016: 
 6017: =cut
 6018: 
 6019: sub lonnet_putfile {
 6020:     my ($contents,$filename)=@_;
 6021:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6022:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6023:     $env{'form.sillywaytopassafilearound'}=$contents;
 6024:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 6025: 
 6026: }
 6027: 
 6028: =pod
 6029: 
 6030: =item scantron_putfile
 6031: 
 6032:     Stores the current version of the bubble sheet data files, and the
 6033:     scan_data hash. (Does not modify the original version only the
 6034:     corrected and skipped versions.
 6035: 
 6036:  Arguments:
 6037:     $scanlines - hash ref that looks like the first return value from
 6038:                  &scantron_getfile()
 6039:     $scan_data - hash ref that looks like the second return value from
 6040:                  &scantron_getfile()
 6041: 
 6042: =cut
 6043: 
 6044: sub scantron_putfile {
 6045:     my ($scanlines,$scan_data) = @_;
 6046:     #FIXME really would prefer a scantron directory
 6047:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6048:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6049:     if ($scanlines) {
 6050: 	my $prefix='scantron_';
 6051: # no need to update orig, shouldn't change
 6052: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6053: #		    $env{'form.scantron_selectfile'});
 6054: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6055: 			$prefix.'corrected_'.
 6056: 			$env{'form.scantron_selectfile'});
 6057: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6058: 			$prefix.'skipped_'.
 6059: 			$env{'form.scantron_selectfile'});
 6060:     }
 6061:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6062: }
 6063: 
 6064: =pod
 6065: 
 6066: =item scantron_get_line
 6067: 
 6068:    Returns the correct version of the scanline
 6069: 
 6070:  Arguments:
 6071:     $scanlines - hash ref that looks like the first return value from
 6072:                  &scantron_getfile()
 6073:     $scan_data - hash ref that looks like the second return value from
 6074:                  &scantron_getfile()
 6075:     $i         - number of the requested line (starts at 0)
 6076: 
 6077:  Returns:
 6078:    A scanline, (either the original or the corrected one if it
 6079:    exists), or undef if the requested scanline should be
 6080:    skipped. (Either because it's an skipped scanline, or it's an
 6081:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6082:    pass.
 6083: 
 6084: =cut
 6085: 
 6086: sub scantron_get_line {
 6087:     my ($scanlines,$scan_data,$i)=@_;
 6088:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6089:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6090:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6091:     return $scanlines->{'orig'}[$i]; 
 6092: }
 6093: 
 6094: =pod
 6095: 
 6096: =item scantron_todo_count
 6097: 
 6098:     Counts the number of scanlines that need processing.
 6099: 
 6100:  Arguments:
 6101:     $scanlines - hash ref that looks like the first return value from
 6102:                  &scantron_getfile()
 6103:     $scan_data - hash ref that looks like the second return value from
 6104:                  &scantron_getfile()
 6105: 
 6106:  Returns:
 6107:     $count - number of scanlines to process
 6108: 
 6109: =cut
 6110: 
 6111: sub get_todo_count {
 6112:     my ($scanlines,$scan_data)=@_;
 6113:     my $count=0;
 6114:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6115: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6116: 	if ($line=~/^[\s\cz]*$/) { next; }
 6117: 	$count++;
 6118:     }
 6119:     return $count;
 6120: }
 6121: 
 6122: =pod
 6123: 
 6124: =item scantron_put_line
 6125: 
 6126:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6127:     data file.
 6128: 
 6129:  Arguments:
 6130:     $scanlines - hash ref that looks like the first return value from
 6131:                  &scantron_getfile()
 6132:     $scan_data - hash ref that looks like the second return value from
 6133:                  &scantron_getfile()
 6134:     $i         - line number to update
 6135:     $newline   - contents of the updated scanline
 6136:     $skip      - if true make the line for skipping and update the
 6137:                  'skipped' file
 6138: 
 6139: =cut
 6140: 
 6141: sub scantron_put_line {
 6142:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6143:     if ($skip) {
 6144: 	$scanlines->{'skipped'}[$i]=$newline;
 6145: 	&start_skipping($scan_data,$i);
 6146: 	return;
 6147:     }
 6148:     $scanlines->{'corrected'}[$i]=$newline;
 6149: }
 6150: 
 6151: =pod
 6152: 
 6153: =item scantron_clear_skip
 6154: 
 6155:    Remove a line from the 'skipped' file
 6156: 
 6157:  Arguments:
 6158:     $scanlines - hash ref that looks like the first return value from
 6159:                  &scantron_getfile()
 6160:     $scan_data - hash ref that looks like the second return value from
 6161:                  &scantron_getfile()
 6162:     $i         - line number to update
 6163: 
 6164: =cut
 6165: 
 6166: sub scantron_clear_skip {
 6167:     my ($scanlines,$scan_data,$i)=@_;
 6168:     if (exists($scanlines->{'skipped'}[$i])) {
 6169: 	undef($scanlines->{'skipped'}[$i]);
 6170: 	return 1;
 6171:     }
 6172:     return 0;
 6173: }
 6174: 
 6175: =pod
 6176: 
 6177: =item scantron_filter_not_exam
 6178: 
 6179:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6180:    filter out resources that are not marked as 'exam' mode
 6181: 
 6182: =cut
 6183: 
 6184: sub scantron_filter_not_exam {
 6185:     my ($curres)=@_;
 6186:     
 6187:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6188: 	# if the user has asked to not have either hidden
 6189: 	# or 'randomout' controlled resources to be graded
 6190: 	# don't include them
 6191: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6192: 	    && $curres->randomout) {
 6193: 	    return 0;
 6194: 	}
 6195: 	return 1;
 6196:     }
 6197:     return 0;
 6198: }
 6199: 
 6200: =pod
 6201: 
 6202: =item scantron_validate_sequence
 6203: 
 6204:     Validates the selected sequence, checking for resource that are
 6205:     not set to exam mode.
 6206: 
 6207: =cut
 6208: 
 6209: sub scantron_validate_sequence {
 6210:     my ($r,$currentphase) = @_;
 6211: 
 6212:     my $navmap=Apache::lonnavmaps::navmap->new();
 6213:     my (undef,undef,$sequence)=
 6214: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6215: 
 6216:     my $map=$navmap->getResourceByUrl($sequence);
 6217: 
 6218:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6219:                                     value="ignore" />');
 6220:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6221: 	my @resources=
 6222: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6223: 	if (@resources) {
 6224: 	    $r->print("<p>".&mt('Some resources in the sequence currently are not set to exam mode. Grading these resources currently may not work correctly.')."</p>");
 6225: 	    return (1,$currentphase);
 6226: 	}
 6227:     }
 6228: 
 6229:     return (0,$currentphase+1);
 6230: }
 6231: 
 6232: =pod
 6233: 
 6234: =item scantron_validate_ID
 6235: 
 6236:    Validates all scanlines in the selected file to not have any
 6237:    invalid or underspecified student IDs
 6238: 
 6239: =cut
 6240: 
 6241: sub scantron_validate_ID {
 6242:     my ($r,$currentphase) = @_;
 6243:     
 6244:     #get student info
 6245:     my $classlist=&Apache::loncoursedata::get_classlist();
 6246:     my %idmap=&username_to_idmap($classlist);
 6247: 
 6248:     #get scantron line setup
 6249:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6250:     my ($scanlines,$scan_data)=&scantron_getfile();
 6251:     
 6252:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6253: 
 6254:     my %found=('ids'=>{},'usernames'=>{});
 6255:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6256: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6257: 	if ($line=~/^[\s\cz]*$/) { next; }
 6258: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6259: 						 $scan_data);
 6260: 	my $id=$$scan_record{'scantron.ID'};
 6261: 	my $found;
 6262: 	foreach my $checkid (keys(%idmap)) {
 6263: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6264: 	}
 6265: 	if ($found) {
 6266: 	    my $username=$idmap{$found};
 6267: 	    if ($found{'ids'}{$found}) {
 6268: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6269: 					 $line,'duplicateID',$found);
 6270: 		return(1,$currentphase);
 6271: 	    } elsif ($found{'usernames'}{$username}) {
 6272: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6273: 					 $line,'duplicateID',$username);
 6274: 		return(1,$currentphase);
 6275: 	    }
 6276: 	    #FIXME store away line we previously saw the ID on to use above
 6277: 	    $found{'ids'}{$found}++;
 6278: 	    $found{'usernames'}{$username}++;
 6279: 	} else {
 6280: 	    if ($id =~ /^\s*$/) {
 6281: 		my $username=&scan_data($scan_data,"$i.user");
 6282: 		if (defined($username) && $found{'usernames'}{$username}) {
 6283: 		    &scantron_get_correction($r,$i,$scan_record,
 6284: 					     \%scantron_config,
 6285: 					     $line,'duplicateID',$username);
 6286: 		    return(1,$currentphase);
 6287: 		} elsif (!defined($username)) {
 6288: 		    &scantron_get_correction($r,$i,$scan_record,
 6289: 					     \%scantron_config,
 6290: 					     $line,'incorrectID');
 6291: 		    return(1,$currentphase);
 6292: 		}
 6293: 		$found{'usernames'}{$username}++;
 6294: 	    } else {
 6295: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6296: 					 $line,'incorrectID');
 6297: 		return(1,$currentphase);
 6298: 	    }
 6299: 	}
 6300:     }
 6301: 
 6302:     return (0,$currentphase+1);
 6303: }
 6304: 
 6305: =pod
 6306: 
 6307: =item scantron_get_correction
 6308: 
 6309:    Builds the interface screen to interact with the operator to fix a
 6310:    specific error condition in a specific scanline
 6311: 
 6312:  Arguments:
 6313:     $r           - Apache request object
 6314:     $i           - number of the current scanline
 6315:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 6316:     $scan_config - hash ref as returned from &get_scantron_config()
 6317:     $line        - full contents of the current scanline
 6318:     $error       - error condition, valid values are
 6319:                    'incorrectCODE', 'duplicateCODE',
 6320:                    'doublebubble', 'missingbubble',
 6321:                    'duplicateID', 'incorrectID'
 6322:     $arg         - extra information needed
 6323:        For errors:
 6324:          - duplicateID   - paper number that this studentID was seen before on
 6325:          - duplicateCODE - array ref of the paper numbers this CODE was
 6326:                            seen on before
 6327:          - incorrectCODE - current incorrect CODE 
 6328:          - doublebubble  - array ref of the bubble lines that have double
 6329:                            bubble errors
 6330:          - missingbubble - array ref of the bubble lines that have missing
 6331:                            bubble errors
 6332: 
 6333: =cut
 6334: 
 6335: sub scantron_get_correction {
 6336:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6337: 
 6338: #FIXME in the case of a duplicated ID the previous line, probably need
 6339: #to show both the current line and the previous one and allow skipping
 6340: #the previous one or the current one
 6341: 
 6342:     $r->print("<p><b>An error was detected ($error)</b>");
 6343:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6344: 	$r->print(" for PaperID <tt>".
 6345: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
 6346:     } else {
 6347: 	$r->print(" in scanline $i <pre>".
 6348: 		  $line."</pre> \n");
 6349:     }
 6350:     my $message="<p>The ID on the form is  <tt>".
 6351: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
 6352: 	"The name on the paper is ".
 6353: 	$$scan_record{'scantron.LastName'}.",".
 6354: 	$$scan_record{'scantron.FirstName'}."</p>";
 6355: 
 6356:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6357:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6358:     if ($error =~ /ID$/) {
 6359: 	if ($error eq 'incorrectID') {
 6360: 	    $r->print("The encoded ID is not in the classlist</p>\n");
 6361: 	} elsif ($error eq 'duplicateID') {
 6362: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
 6363: 	}
 6364: 	$r->print($message);
 6365: 	$r->print("<p>How should I handle this? <br /> \n");
 6366: 	$r->print("\n<ul><li> ");
 6367: 	#FIXME it would be nice if this sent back the user ID and
 6368: 	#could do partial userID matches
 6369: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6370: 				       'scantron_username','scantron_domain'));
 6371: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6372: 	$r->print("\n@".
 6373: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6374: 
 6375: 	$r->print('</li>');
 6376:     } elsif ($error =~ /CODE$/) {
 6377: 	if ($error eq 'incorrectCODE') {
 6378: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
 6379: 	} elsif ($error eq 'duplicateCODE') {
 6380: 	    $r->print("</p><p>The encoded CODE has also been used by a previous paper ".join(', ',@{$arg}).", and CODEs are supposed to be unique</p>\n");
 6381: 	}
 6382: 	$r->print("<p>The CODE on the form is  <tt>'".
 6383: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
 6384: 	$r->print($message);
 6385: 	$r->print("<p>How should I handle this? <br /> \n");
 6386: 	$r->print("\n<br /> ");
 6387: 	my $i=0;
 6388: 	if ($error eq 'incorrectCODE' 
 6389: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6390: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6391: 	    if ($closest > 0) {
 6392: 		foreach my $testcode (@{$closest}) {
 6393: 		    my $checked='';
 6394: 		    if (!$i) { $checked=' checked="checked" '; }
 6395: 		    $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked /> Use the similar CODE <b><tt>".$testcode."</tt></b> instead.</label><input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
 6396: 		    $r->print("\n<br />");
 6397: 		    $i++;
 6398: 		}
 6399: 	    }
 6400: 	}
 6401: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6402: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6403: 	    $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked /> Use the CODE <b><tt>".$$scan_record{'scantron.CODE'}."</tt></b> that is was on the paper, ignoring the error.</label>");
 6404: 	    $r->print("\n<br />");
 6405: 	}
 6406: 
 6407: 	$r->print(<<ENDSCRIPT);
 6408: <script type="text/javascript">
 6409: function change_radio(field) {
 6410:     var slct=document.scantronupload.scantron_CODE_resolution;
 6411:     var i;
 6412:     for (i=0;i<slct.length;i++) {
 6413:         if (slct[i].value==field) { slct[i].checked=true; }
 6414:     }
 6415: }
 6416: </script>
 6417: ENDSCRIPT
 6418: 	my $href="/adm/pickcode?".
 6419: 	   "form=".&escape("scantronupload").
 6420: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6421: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6422: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6423: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6424: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6425: 	    $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_found' /> <a target='_blank' href='$href'>Select</a> a CODE from the list of all CODEs and use it.</label> Selected CODE is <input readonly='true' type='text' size='8' name='scantron_CODE_selectedvalue' onfocus=\"javascript:change_radio('use_found')\" onchange=\"javascript:change_radio('use_found')\" />");
 6426: 	    $r->print("\n<br />");
 6427: 	}
 6428: 	$r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_typed' /> Use </label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" /> as the CODE.");
 6429: 	$r->print("\n<br /><br />");
 6430:     } elsif ($error eq 'doublebubble') {
 6431: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
 6432: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6433: 		  join(',',@{$arg}).'" />');
 6434: 	$r->print($message);
 6435: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
 6436: 	foreach my $question (@{$arg}) {
 6437: 	    my $selected  = &get_response_bubbles($scan_record, $question);
 6438: 	    my @select_array = split(/:/,$selected);
 6439: 	    &scantron_bubble_selector($r,$scan_config,$question,
 6440: 				      @select_array);
 6441: 	}
 6442:     } elsif ($error eq 'missingbubble') {
 6443: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
 6444: 	$r->print($message);
 6445: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
 6446: 	$r->print("Some questions have no scanned bubbles\n");
 6447: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6448: 		  join(',',@{$arg}).'" />');
 6449: 	foreach my $question (@{$arg}) {
 6450: 	    my $selected = &get_response_bubbles($scan_record, $question);
 6451: 	    &scantron_bubble_selector($r,$scan_config,$question);
 6452: 	}
 6453:     } else {
 6454: 	$r->print("\n<ul>");
 6455:     }
 6456:     $r->print("\n</li></ul>");
 6457: 
 6458: }
 6459: 
 6460: =pod
 6461: 
 6462: =item scantron_bubble_selector
 6463:   
 6464:    Generates the html radiobuttons to correct a single bubble line
 6465:    possibly showing the existing the selected bubbles if known
 6466: 
 6467:  Arguments:
 6468:     $r           - Apache request object
 6469:     $scan_config - hash from &get_scantron_config()
 6470:     $quest       - number of the bubble line to make a corrector for
 6471:     $lines       - array of answer lines.
 6472: 
 6473: =cut
 6474: 
 6475: sub scantron_bubble_selector {
 6476:     my ($r,$scan_config,$quest,@lines)=@_;
 6477:     my $max=$$scan_config{'Qlength'};
 6478: 
 6479: 
 6480:     my $scmode=$$scan_config{'Qon'};
 6481: 
 6482:     my $bubble_length = scalar(@lines);
 6483: 
 6484: 
 6485:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 6486: 
 6487:     my $response = $quest-1;
 6488:     my $lines = $bubble_lines_per_response{$response};
 6489: 
 6490:     my $total_lines = $lines*2;
 6491:     my @alphabet=('A'..'Z');
 6492:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
 6493: 
 6494:     for (my $l = 0; $l < $lines; $l++) {
 6495: 	if ($l != 0) {
 6496: 	    $r->print('<tr>');
 6497: 	}
 6498: 	my @selected = split(//,$lines[$l]);
 6499: 	for (my $i=0;$i<$max;$i++) {
 6500: 	    $r->print("\n".'<td align="center">');
 6501: 	    if ($selected[0] eq $alphabet[$i]) { 
 6502: 		$r->print('X'); 
 6503: 		shift(@selected) ;
 6504: 	    } else { 
 6505: 		$r->print('&nbsp;'); 
 6506: 	    }
 6507: 	    $r->print('</td>');
 6508: 	    
 6509: 	}
 6510: 
 6511: 	if ($l == 0) {
 6512: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
 6513: 
 6514: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
 6515: 	      $quest.'" value="none" /> No bubble </label></td>');
 6516: 	
 6517: 	}
 6518: 
 6519: 	$r->print('</tr><tr>');
 6520: 
 6521: 	# FIXME: This may have to be a bit more clever for
 6522: 	#        multiline questions (different values e.g..).
 6523: 
 6524: 	for (my $i=0;$i<$max;$i++) {
 6525: 	    $r->print("\n".
 6526: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
 6527: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 6528: 	}
 6529: 	$r->print('</tr>');
 6530: 
 6531: 	    
 6532:     }
 6533:     $r->print('</table>');
 6534: }
 6535: 
 6536: =pod
 6537: 
 6538: =item num_matches
 6539: 
 6540:    Counts the number of characters that are the same between the two arguments.
 6541: 
 6542:  Arguments:
 6543:    $orig - CODE from the scanline
 6544:    $code - CODE to match against
 6545: 
 6546:  Returns:
 6547:    $count - integer count of the number of same characters between the
 6548:             two arguments
 6549: 
 6550: =cut
 6551: 
 6552: sub num_matches {
 6553:     my ($orig,$code) = @_;
 6554:     my @code=split(//,$code);
 6555:     my @orig=split(//,$orig);
 6556:     my $same=0;
 6557:     for (my $i=0;$i<scalar(@code);$i++) {
 6558: 	if ($code[$i] eq $orig[$i]) { $same++; }
 6559:     }
 6560:     return $same;
 6561: }
 6562: 
 6563: =pod
 6564: 
 6565: =item scantron_get_closely_matching_CODEs
 6566: 
 6567:    Cycles through all CODEs and finds the set that has the greatest
 6568:    number of same characters as the provided CODE
 6569: 
 6570:  Arguments:
 6571:    $allcodes - hash ref returned by &get_codes()
 6572:    $CODE     - CODE from the current scanline
 6573: 
 6574:  Returns:
 6575:    2 element list
 6576:     - first elements is number of how closely matching the best fit is 
 6577:       (5 means best set has 5 matching characters)
 6578:     - second element is an arrary ref containing the set of valid CODEs
 6579:       that best fit the passed in CODE
 6580: 
 6581: =cut
 6582: 
 6583: sub scantron_get_closely_matching_CODEs {
 6584:     my ($allcodes,$CODE)=@_;
 6585:     my @CODEs;
 6586:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 6587: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 6588:     }
 6589: 
 6590:     return ($#CODEs,$CODEs[-1]);
 6591: }
 6592: 
 6593: =pod
 6594: 
 6595: =item get_codes
 6596: 
 6597:    Builds a hash which has keys of all of the valid CODEs from the selected
 6598:    set of remembered CODEs.
 6599: 
 6600:  Arguments:
 6601:   $old_name - name of the set of remembered CODEs
 6602:   $cdom     - domain of the course
 6603:   $cnum     - internal course name
 6604: 
 6605:  Returns:
 6606:   %allcodes - keys are the valid CODEs, values are all 1
 6607: 
 6608: =cut
 6609: 
 6610: sub get_codes {
 6611:     my ($old_name, $cdom, $cnum) = @_;
 6612:     if (!$old_name) {
 6613: 	$old_name=$env{'form.scantron_CODElist'};
 6614:     }
 6615:     if (!$cdom) {
 6616: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 6617:     }
 6618:     if (!$cnum) {
 6619: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 6620:     }
 6621:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 6622: 				    $cdom,$cnum);
 6623:     my %allcodes;
 6624:     if ($result{"type\0$old_name"} eq 'number') {
 6625: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 6626:     } else {
 6627: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 6628:     }
 6629:     return %allcodes;
 6630: }
 6631: 
 6632: =pod
 6633: 
 6634: =item scantron_validate_CODE
 6635: 
 6636:    Validates all scanlines in the selected file to not have any
 6637:    invalid or underspecified CODEs and that none of the codes are
 6638:    duplicated if this was requested.
 6639: 
 6640: =cut
 6641: 
 6642: sub scantron_validate_CODE {
 6643:     my ($r,$currentphase) = @_;
 6644:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6645:     if ($scantron_config{'CODElocation'} &&
 6646: 	$scantron_config{'CODEstart'} &&
 6647: 	$scantron_config{'CODElength'}) {
 6648: 	if (!defined($env{'form.scantron_CODElist'})) {
 6649: 	    &FIXME_blow_up()
 6650: 	}
 6651:     } else {
 6652: 	return (0,$currentphase+1);
 6653:     }
 6654:     
 6655:     my %usedCODEs;
 6656: 
 6657:     my %allcodes=&get_codes();
 6658: 
 6659:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 6660: 
 6661:     my ($scanlines,$scan_data)=&scantron_getfile();
 6662:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6663: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6664: 	if ($line=~/^[\s\cz]*$/) { next; }
 6665: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6666: 						 $scan_data);
 6667: 	my $CODE=$$scan_record{'scantron.CODE'};
 6668: 	my $error=0;
 6669: 	if (!&Apache::lonnet::validCODE($CODE)) {
 6670: 	    &scantron_get_correction($r,$i,$scan_record,
 6671: 				     \%scantron_config,
 6672: 				     $line,'incorrectCODE',\%allcodes);
 6673: 	    return(1,$currentphase);
 6674: 	}
 6675: 	if (%allcodes && !exists($allcodes{$CODE}) 
 6676: 	    && !$$scan_record{'scantron.useCODE'}) {
 6677: 	    &scantron_get_correction($r,$i,$scan_record,
 6678: 				     \%scantron_config,
 6679: 				     $line,'incorrectCODE',\%allcodes);
 6680: 	    return(1,$currentphase);
 6681: 	}
 6682: 	if (exists($usedCODEs{$CODE}) 
 6683: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 6684: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 6685: 	    &scantron_get_correction($r,$i,$scan_record,
 6686: 				     \%scantron_config,
 6687: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 6688: 	    return(1,$currentphase);
 6689: 	}
 6690: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 6691:     }
 6692:     return (0,$currentphase+1);
 6693: }
 6694: 
 6695: =pod
 6696: 
 6697: =item scantron_validate_doublebubble
 6698: 
 6699:    Validates all scanlines in the selected file to not have any
 6700:    bubble lines with multiple bubbles marked.
 6701: 
 6702: =cut
 6703: 
 6704: sub scantron_validate_doublebubble {
 6705:     my ($r,$currentphase) = @_;
 6706:     #get student info
 6707:     my $classlist=&Apache::loncoursedata::get_classlist();
 6708:     my %idmap=&username_to_idmap($classlist);
 6709: 
 6710:     #get scantron line setup
 6711:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6712:     my ($scanlines,$scan_data)=&scantron_getfile();
 6713: 
 6714:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 6715: 
 6716:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6717: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6718: 	if ($line=~/^[\s\cz]*$/) { next; }
 6719: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6720: 						 $scan_data);
 6721: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 6722: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 6723: 				 'doublebubble',
 6724: 				 $$scan_record{'scantron.doubleerror'});
 6725:     	return (1,$currentphase);
 6726:     }
 6727:     return (0,$currentphase+1);
 6728: }
 6729: 
 6730: =pod
 6731: 
 6732: =item scantron_get_maxbubble
 6733: 
 6734:    Returns the maximum number of bubble lines that are expected to
 6735:    occur. Does this by walking the selected sequence rendering the
 6736:    resource and then checking &Apache::lonxml::get_problem_counter()
 6737:    for what the current value of the problem counter is.
 6738: 
 6739:    Caches the results to $env{'form.scantron_maxbubble'},
 6740:    $env{'form.scantron.bubble_lines.n'} and 
 6741:    $env{'form.scantron.first_bubble_line.n'}
 6742:    which are the total number of bubble, lines, the number of bubble
 6743:    lines for reponse n and number of the first bubble line for response n.
 6744: 
 6745: =cut
 6746: 
 6747: sub scantron_get_maxbubble {    
 6748:     if (defined($env{'form.scantron_maxbubble'}) &&
 6749: 	$env{'form.scantron_maxbubble'}) {
 6750: 	&restore_bubble_lines();
 6751: 	return $env{'form.scantron_maxbubble'};
 6752:     }
 6753: 
 6754:     my (undef, undef, $sequence) =
 6755: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6756: 
 6757:     my $navmap=Apache::lonnavmaps::navmap->new();
 6758:     my $map=$navmap->getResourceByUrl($sequence);
 6759:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 6760: 
 6761:     &Apache::lonxml::clear_problem_counter();
 6762: 
 6763:     my $uname       = $env{'form.student'};
 6764:     my $udom        = $env{'form.userdom'};
 6765:     my $cid         = $env{'request.course.id'};
 6766:     my $total_lines = 0;
 6767:     %bubble_lines_per_response = ();
 6768:     %first_bubble_line         = ();
 6769: 
 6770:   
 6771:     my $response_number = 0;
 6772:     my $bubble_line     = 0;
 6773:     foreach my $resource (@resources) {
 6774: 	my $symb = $resource->symb();
 6775: 	&Apache::lonxml::clear_bubble_lines_for_part();
 6776: 	my $result=&Apache::lonnet::ssi($resource->src(),
 6777: 					('symb' => $resource->symb()),
 6778: 					('grade_target' => 'analyze'),
 6779: 					('grade_courseid' => $cid),
 6780: 					('grade_domain' => $udom),
 6781: 					('grade_username' => $uname));
 6782: 	my (undef, $an) =
 6783: 	    split(/_HASH_REF__/,$result, 2);
 6784: 
 6785: 	my %analysis = &Apache::lonnet::str2hash($an);
 6786: 
 6787: 
 6788: 
 6789: 	foreach my $part_id (@{$analysis{'parts'}}) {
 6790: 
 6791: 
 6792: 	    my $lines = $analysis{"$part_id.bubble_lines"};;
 6793: 
 6794: 	    # TODO - make this a persistent hash not an array.
 6795: 
 6796: 
 6797: 	    $first_bubble_line{$response_number}           = $bubble_line;
 6798: 	    $bubble_lines_per_response{$response_number}   = $lines;
 6799: 	    $response_number++;
 6800: 
 6801: 	    $bubble_line +=  $lines;
 6802: 	    $total_lines +=  $lines;
 6803: 	}
 6804: 
 6805:     }
 6806:     &Apache::lonnet::delenv('scantron\.');
 6807: 
 6808:     &save_bubble_lines();
 6809:     $env{'form.scantron_maxbubble'} =
 6810: 	$total_lines;
 6811:     return $env{'form.scantron_maxbubble'};
 6812: }
 6813: 
 6814: =pod
 6815: 
 6816: =item scantron_validate_missingbubbles
 6817: 
 6818:    Validates all scanlines in the selected file to not have any
 6819:     answers that don't have bubbles that have not been verified
 6820:     to be bubble free.
 6821: 
 6822: =cut
 6823: 
 6824: sub scantron_validate_missingbubbles {
 6825:     my ($r,$currentphase) = @_;
 6826:     #get student info
 6827:     my $classlist=&Apache::loncoursedata::get_classlist();
 6828:     my %idmap=&username_to_idmap($classlist);
 6829: 
 6830:     #get scantron line setup
 6831:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6832:     my ($scanlines,$scan_data)=&scantron_getfile();
 6833:     my $max_bubble=&scantron_get_maxbubble();
 6834:     if (!$max_bubble) { $max_bubble=2**31; }
 6835:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6836: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6837: 	if ($line=~/^[\s\cz]*$/) { next; }
 6838: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6839: 						 $scan_data);
 6840: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 6841: 	my @to_correct;
 6842: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 6843: 	    if ($missing > $max_bubble) { next; }
 6844: 	    push(@to_correct,$missing);
 6845: 	}
 6846: 	if (@to_correct) {
 6847: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6848: 				     $line,'missingbubble',\@to_correct);
 6849: 	    return (1,$currentphase);
 6850: 	}
 6851: 
 6852:     }
 6853:     return (0,$currentphase+1);
 6854: }
 6855: 
 6856: =pod
 6857: 
 6858: =item scantron_process_students
 6859: 
 6860:    Routine that does the actual grading of the bubble sheet information.
 6861: 
 6862:    The parsed scanline hash is added to %env 
 6863: 
 6864:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 6865:    foreach resource , with the form data of
 6866: 
 6867: 	'submitted'     =>'scantron' 
 6868: 	'grade_target'  =>'grade',
 6869: 	'grade_username'=> username of student
 6870: 	'grade_domain'  => domain of student
 6871: 	'grade_courseid'=> of course
 6872: 	'grade_symb'    => symb of resource to grade
 6873: 
 6874:     This triggers a grading pass. The problem grading code takes care
 6875:     of converting the bubbled letter information (now in %env) into a
 6876:     valid submission.
 6877: 
 6878: =cut
 6879: 
 6880: sub scantron_process_students {
 6881:     my ($r) = @_;
 6882:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6883:     my ($symb)=&get_symb($r);
 6884:     if (!$symb) {return '';}
 6885:     my $default_form_data=&defaultFormData($symb);
 6886: 
 6887:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6888:     my ($scanlines,$scan_data)=&scantron_getfile();
 6889:     my $classlist=&Apache::loncoursedata::get_classlist();
 6890:     my %idmap=&username_to_idmap($classlist);
 6891:     my $navmap=Apache::lonnavmaps::navmap->new();
 6892:     my $map=$navmap->getResourceByUrl($sequence);
 6893:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 6894: #    $r->print("geto ".scalar(@resources)."<br />");
 6895:     my $result= <<SCANTRONFORM;
 6896: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6897:   <input type="hidden" name="command" value="scantron_configphase" />
 6898:   $default_form_data
 6899: SCANTRONFORM
 6900:     $r->print($result);
 6901: 
 6902:     my @delayqueue;
 6903:     my %completedstudents;
 6904:     
 6905:     my $count=&get_todo_count($scanlines,$scan_data);
 6906:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 6907:  				    'Scantron Progress',$count,
 6908: 				    'inline',undef,'scantronupload');
 6909:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 6910: 					  'Processing first student');
 6911:     my $start=&Time::HiRes::time();
 6912:     my $i=-1;
 6913:     my ($uname,$udom,$started);
 6914: 
 6915:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 6916: 
 6917:     while ($i<$scanlines->{'count'}) {
 6918:  	($uname,$udom)=('','');
 6919:  	$i++;
 6920:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6921:  	if ($line=~/^[\s\cz]*$/) { next; }
 6922: 	if ($started) {
 6923: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 6924: 						     'last student');
 6925: 	}
 6926: 	$started=1;
 6927:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6928:  						 $scan_data);
 6929:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 6930:  					      \%idmap,$i)) {
 6931:   	    &scantron_add_delay(\@delayqueue,$line,
 6932:  				'Unable to find a student that matches',1);
 6933:  	    next;
 6934:   	}
 6935:  	if (exists $completedstudents{$uname}) {
 6936:  	    &scantron_add_delay(\@delayqueue,$line,
 6937:  				'Student '.$uname.' has multiple sheets',2);
 6938:  	    next;
 6939:  	}
 6940:   	($uname,$udom)=split(/:/,$uname);
 6941: 
 6942: 	&Apache::lonxml::clear_problem_counter();
 6943:   	&Apache::lonnet::appenv(%$scan_record);
 6944: 
 6945: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 6946: 	    &scantron_putfile($scanlines,$scan_data);
 6947: 	}
 6948: 	
 6949: 	my $i=0;
 6950: 	foreach my $resource (@resources) {
 6951: 	    $i++;
 6952: 	    my %form=('submitted'     =>'scantron',
 6953: 		      'grade_target'  =>'grade',
 6954: 		      'grade_username'=>$uname,
 6955: 		      'grade_domain'  =>$udom,
 6956: 		      'grade_courseid'=>$env{'request.course.id'},
 6957: 		      'grade_symb'    =>$resource->symb());
 6958: 	    if (exists($scan_record->{'scantron.CODE'})
 6959: 		&& 
 6960: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
 6961: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
 6962: 	    } else {
 6963: 		$form{'CODE'}='';
 6964: 	    }
 6965: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
 6966: 	    if ($result ne '') {
 6967: 	    }
 6968: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
 6969: 	}
 6970: 	$completedstudents{$uname}={'line'=>$line};
 6971: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
 6972:     } continue {
 6973: 	&Apache::lonxml::clear_problem_counter();
 6974: 	&Apache::lonnet::delenv('scantron\.');
 6975:     }
 6976:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 6977: #    my $lasttime = &Time::HiRes::time()-$start;
 6978: #    $r->print("<p>took $lasttime</p>");
 6979: 
 6980:     $r->print("</form>");
 6981:     $r->print(&show_grading_menu_form($symb));
 6982:     return '';
 6983: }
 6984: 
 6985: =pod
 6986: 
 6987: =item scantron_upload_scantron_data
 6988: 
 6989:     Creates the screen for adding a new bubble sheet data file to a course.
 6990: 
 6991: =cut
 6992: 
 6993: sub scantron_upload_scantron_data {
 6994:     my ($r)=@_;
 6995:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 6996:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 6997: 							  'domainid',
 6998: 							  'coursename');
 6999:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 7000: 						   'domainid');
 7001:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7002:     $r->print(<<UPLOAD);
 7003: <script type="text/javascript" language="javascript">
 7004:     function checkUpload(formname) {
 7005: 	if (formname.upfile.value == "") {
 7006: 	    alert("Please use the browse button to select a file from your local directory.");
 7007: 	    return false;
 7008: 	}
 7009: 	formname.submit();
 7010:     }
 7011: </script>
 7012: 
 7013: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
 7014: $default_form_data
 7015: <table>
 7016: <tr><td>$select_link </td></tr>
 7017: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
 7018: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
 7019: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
 7020: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
 7021: </table>
 7022: <input name='command' value='scantronupload_save' type='hidden' />
 7023: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
 7024: </form>
 7025: UPLOAD
 7026:     return '';
 7027: }
 7028: 
 7029: =pod
 7030: 
 7031: =item scantron_upload_scantron_data_save
 7032: 
 7033:    Adds a provided bubble information data file to the course if user
 7034:    has the correct privileges to do so.  
 7035: 
 7036: =cut
 7037: 
 7038: sub scantron_upload_scantron_data_save {
 7039:     my($r)=@_;
 7040:     my ($symb)=&get_symb($r,1);
 7041:     my $doanotherupload=
 7042: 	'<br /><form action="/adm/grades" method="post">'."\n".
 7043: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7044: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
 7045: 	'</form>'."\n";
 7046:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7047: 	!&Apache::lonnet::allowed('usc',
 7048: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7049: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
 7050: 	if ($symb) {
 7051: 	    $r->print(&show_grading_menu_form($symb));
 7052: 	} else {
 7053: 	    $r->print($doanotherupload);
 7054: 	}
 7055: 	return '';
 7056:     }
 7057:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7058:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
 7059:     my $fname=$env{'form.upfile.filename'};
 7060:     #FIXME
 7061:     #copied from lonnet::userfileupload()
 7062:     #make that function able to target a specified course
 7063:     # Replace Windows backslashes by forward slashes
 7064:     $fname=~s/\\/\//g;
 7065:     # Get rid of everything but the actual filename
 7066:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7067:     # Replace spaces by underscores
 7068:     $fname=~s/\s+/\_/g;
 7069:     # Replace all other weird characters by nothing
 7070:     $fname=~s/[^\w\.\-]//g;
 7071:     # See if there is anything left
 7072:     unless ($fname) { return 'error: no uploaded file'; }
 7073:     my $uploadedfile=$fname;
 7074:     $fname='scantron_orig_'.$fname;
 7075:     if (length($env{'form.upfile'}) < 2) {
 7076: 	$r->print("<span class=\"LC_error\">Error:</span> The file you attempted to upload, <tt>".&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</tt>, contained no information. Please check that you entered the correct filename.");
 7077:     } else {
 7078: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7079: 	if ($result =~ m|^/uploaded/|) {
 7080: 	    $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
 7081: 	} else {
 7082: 	    $r->print("<span class=\"LC_error\">Error:</span> An error (".$result.") occurred when attempting to upload the file, <tt>".&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</tt>");
 7083: 	}
 7084:     }
 7085:     if ($symb) {
 7086: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7087:     } else {
 7088: 	$r->print($doanotherupload);
 7089:     }
 7090:     return '';
 7091: }
 7092: 
 7093: =pod
 7094: 
 7095: =item valid_file
 7096: 
 7097:    Validates that the requested bubble data file exists in the course.
 7098: 
 7099: =cut
 7100: 
 7101: sub valid_file {
 7102:     my ($requested_file)=@_;
 7103:     foreach my $filename (sort(&scantron_filenames())) {
 7104: 	if ($requested_file eq $filename) { return 1; }
 7105:     }
 7106:     return 0;
 7107: }
 7108: 
 7109: =pod
 7110: 
 7111: =item scantron_download_scantron_data
 7112: 
 7113:    Shows a list of the three internal files (original, corrected,
 7114:    skipped) for a specific bubble sheet data file that exists in the
 7115:    course.
 7116: 
 7117: =cut
 7118: 
 7119: sub scantron_download_scantron_data {
 7120:     my ($r)=@_;
 7121:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7122:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7123:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7124:     my $file=$env{'form.scantron_selectfile'};
 7125:     if (! &valid_file($file)) {
 7126: 	$r->print(<<ERROR);
 7127: 	<p>
 7128: 	    The requested file name was invalid.
 7129:         </p>
 7130: ERROR
 7131: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7132: 	return;
 7133:     }
 7134:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7135:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7136:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7137:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7138:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7139:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7140:     $r->print(<<DOWNLOAD);
 7141:     <p>
 7142: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
 7143:     </p>
 7144:     <p>
 7145: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
 7146:     </p>
 7147:     <p>
 7148: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
 7149:     </p>
 7150: DOWNLOAD
 7151:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7152:     return '';
 7153: }
 7154: 
 7155: =pod
 7156: 
 7157: =back
 7158: 
 7159: =cut
 7160: 
 7161: #-------- end of section for handling grading scantron forms -------
 7162: #
 7163: #-------------------------------------------------------------------
 7164: 
 7165: #-------------------------- Menu interface -------------------------
 7166: #
 7167: #--- Show a Grading Menu button - Calls the next routine ---
 7168: sub show_grading_menu_form {
 7169:     my ($symb)=@_;
 7170:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 7171: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7172: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 7173: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 7174: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
 7175: 	'</form>'."\n";
 7176:     return $result;
 7177: }
 7178: 
 7179: # -- Retrieve choices for grading form
 7180: sub savedState {
 7181:     my %savedState = ();
 7182:     if ($env{'form.saveState'}) {
 7183: 	foreach (split(/:/,$env{'form.saveState'})) {
 7184: 	    my ($key,$value) = split(/=/,$_,2);
 7185: 	    $savedState{$key} = $value;
 7186: 	}
 7187:     }
 7188:     return \%savedState;
 7189: }
 7190: 
 7191: sub grading_menu {
 7192:     my ($request) = @_;
 7193:     my ($symb)=&get_symb($request);
 7194:     if (!$symb) {return '';}
 7195:     my $probTitle = &Apache::lonnet::gettitle($symb);
 7196:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 7197: 
 7198:     $request->print($table);
 7199:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 7200:                   'handgrade'=>$hdgrade,
 7201:                   'probTitle'=>$probTitle,
 7202:                   'command'=>'submit_options',
 7203:                   'saveState'=>"",
 7204:                   'gradingMenu'=>1,
 7205:                   'showgrading'=>"yes");
 7206:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7207:     my @menu = ({ url => $url,
 7208:                      name => &mt('Manual Grading/View Submissions'),
 7209:                      short_description => 
 7210:     &mt('Start the process of hand grading submissions.'),
 7211:                  });
 7212:     $fields{'command'} = 'csvform';
 7213:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7214:     push (@menu, { url => $url,
 7215:                    name => &mt('Upload Scores'),
 7216:                    short_description => 
 7217:             &mt('Specify a file containing the class scores for current resource.')});
 7218:     $fields{'command'} = 'processclicker';
 7219:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7220:     push (@menu, { url => $url,
 7221:                    name => &mt('Process Clicker'),
 7222:                    short_description => 
 7223:             &mt('Specify a file containing the clicker information for this resource.')});
 7224:     $fields{'command'} = 'scantron_selectphase';
 7225:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7226:     push (@menu, { url => $url,
 7227:                    name => &mt('Grade/Manage Scantron Forms'),
 7228:                    short_description => 
 7229:             &mt('')});
 7230:     $fields{'command'} = 'verify';
 7231:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7232:     push (@menu, { url => "",
 7233:                    name => &mt('Verify Receipt'),
 7234:                    short_description => 
 7235:             &mt('')});
 7236:     #
 7237:     # Create the menu
 7238:     my $Str;
 7239:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 7240:     $Str .= '<form method="post" action="" name="gradingMenu">';
 7241:     $Str .= '<input type="hidden" name="command" value="" />'.
 7242:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7243: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 7244: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
 7245: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 7246: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 7247: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 7248: 
 7249:     foreach my $menudata (@menu) {
 7250:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
 7251:             $Str .='    <h3><a '.
 7252:                 $menudata->{'jscript'}.
 7253:                 ' href="'.
 7254:                 $menudata->{'url'}.'" >'.
 7255:                 $menudata->{'name'}."</a></h3>\n";
 7256:         } else {
 7257:             $Str .='    <h3><input type="button" value="Verify Receipt" '.
 7258:                 $menudata->{'jscript'}.
 7259:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
 7260:                 ' /></h3>';
 7261:             $Str .= ('&nbsp;'x8).
 7262:                     ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
 7263:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 7264:         }
 7265:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
 7266:             "\n";
 7267:     }
 7268:     $Str .="</dl>\n";
 7269:     $Str .="</form>\n";
 7270:     $request->print(<<GRADINGMENUJS);
 7271: <script type="text/javascript" language="javascript">
 7272:     function checkChoice(formname,val,cmdx) {
 7273: 	if (val <= 2) {
 7274: 	    var cmd = radioSelection(formname.radioChoice);
 7275: 	    var cmdsave = cmd;
 7276: 	} else {
 7277: 	    cmd = cmdx;
 7278: 	    cmdsave = 'submission';
 7279: 	}
 7280: 	formname.command.value = cmd;
 7281: 	if (val < 5) formname.submit();
 7282: 	if (val == 5) {
 7283: 	    if (!checkReceiptNo(formname,'notOK')) { 
 7284: 	        return false;
 7285: 	    } else {
 7286: 	        formname.submit();
 7287: 	    }
 7288: 	}
 7289:     }
 7290: 
 7291:     function checkReceiptNo(formname,nospace) {
 7292: 	var receiptNo = formname.receipt.value;
 7293: 	var checkOpt = false;
 7294: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 7295: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 7296: 	if (checkOpt) {
 7297: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 7298: 	    formname.receipt.value = "";
 7299: 	    formname.receipt.focus();
 7300: 	    return false;
 7301: 	}
 7302: 	return true;
 7303:     }
 7304: </script>
 7305: GRADINGMENUJS
 7306:     &commonJSfunctions($request);
 7307:     return $Str;    
 7308: }
 7309: 
 7310: 
 7311: #--- Displays the submissions first page -------
 7312: sub submit_options {
 7313:     my ($request) = @_;
 7314:     my ($symb)=&get_symb($request);
 7315:     if (!$symb) {return '';}
 7316:     my $probTitle = &Apache::lonnet::gettitle($symb);
 7317: 
 7318:     $request->print(<<GRADINGMENUJS);
 7319: <script type="text/javascript" language="javascript">
 7320:     function checkChoice(formname,val,cmdx) {
 7321: 	if (val <= 2) {
 7322: 	    var cmd = radioSelection(formname.radioChoice);
 7323: 	    var cmdsave = cmd;
 7324: 	} else {
 7325: 	    cmd = cmdx;
 7326: 	    cmdsave = 'submission';
 7327: 	}
 7328: 	formname.command.value = cmd;
 7329: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 7330: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 7331: 	if (val < 5) formname.submit();
 7332: 	if (val == 5) {
 7333: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 7334: 	    formname.submit();
 7335: 	}
 7336: 	if (val < 7) formname.submit();
 7337:     }
 7338: 
 7339:     function checkReceiptNo(formname,nospace) {
 7340: 	var receiptNo = formname.receipt.value;
 7341: 	var checkOpt = false;
 7342: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 7343: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 7344: 	if (checkOpt) {
 7345: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 7346: 	    formname.receipt.value = "";
 7347: 	    formname.receipt.focus();
 7348: 	    return false;
 7349: 	}
 7350: 	return true;
 7351:     }
 7352: </script>
 7353: GRADINGMENUJS
 7354:     &commonJSfunctions($request);
 7355:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
 7356:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 7357:     $result.=$table;
 7358:     my (undef,$sections) = &getclasslist('all','0');
 7359:     my $savedState = &savedState();
 7360:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 7361:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 7362:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 7363:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 7364: 
 7365:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 7366: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7367: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 7368: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 7369: 	'<input type="hidden" name="command"     value="" />'."\n".
 7370: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 7371: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 7372: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 7373: 
 7374:     $result.='<table border="0"><tr><td bgcolor=#777777>'."\n".
 7375: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n".
 7376: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
 7377: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
 7378: 
 7379:     $result.='<table width="100%" border="0">';
 7380:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
 7381:     $result.='<td><b>'.&mt('Sections').'</b></td>';
 7382:     $result.='<td><b>'.&mt('Groups').'</b></td>';
 7383:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
 7384:     $result.='<td><b>'.&mt('Submission Status').'</td>'."\n";
 7385:     $result.='</tr>';
 7386:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
 7387: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
 7388:     if (ref($sections)) {
 7389: 	foreach (sort (@$sections)) {
 7390: 	    $result.='<option value="'.$_.'" '.
 7391: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
 7392: 	}
 7393:     }
 7394:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 7395:     $result.= '</td><td>'."\n";
 7396:     $result.= &Apache::lonstatistics::GroupSelect('group','multiple',3);
 7397:     $result.='</td><td>'."\n";
 7398:     $result.=&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,3,undef,'mult');
 7399: 
 7400:     $result.='</td>';
 7401:     $result.='<td><select name="submitonly" size="3">'.
 7402: 	'<option value="yes" '.
 7403: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
 7404: 	'<option value="queued" '.
 7405: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
 7406: 	'<option value="graded" '.
 7407: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
 7408: 	'<option value="incorrect" '.
 7409: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
 7410: 	'<option value="all" '.
 7411: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>';
 7412: 
 7413:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3"><label>'.
 7414: 	'<input type="radio" name="radioChoice" value="submission" '.
 7415: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
 7416: 	'</label> </td></tr>'."\n";
 7417: 
 7418:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3">'.
 7419: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
 7420: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 7421: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
 7422: 
 7423:     $result.='<tr bgcolor="#ffffe6"><td colspan="3"><br />'.
 7424: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
 7425: 	'</td></tr>'."\n";
 7426: 
 7427: 
 7428:     $result.='<tr bgcolor="#ffffe6" valign="top"><td colspan="3">'.
 7429: 	'<br /><label><input type="radio" name="radioChoice" value="pickStudentPage" '.
 7430: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 7431: 	'The <b>complete</b> set/page/sequence/folder: For one student</label></td></tr>'."\n";
 7432: 
 7433:     $result.='<tr bgcolor="#ffffe6"><td colspan="3"><br />'.
 7434: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
 7435: 	'</td></tr></table>'."\n";
 7436: 
 7437:     $result.='</td>'; #<td valign="top">';
 7438: 
 7439: #    $result.='<table width="100%" border="0">';
 7440: #    $result.='<tr bgcolor="#ffffe6"><td>'.
 7441: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
 7442: #	' '.&mt('scores from file').' </td></tr>'."\n";
 7443: #
 7444: #    $result.='<tr bgcolor="#ffffe6"><td>'.
 7445: #        '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
 7446: #        ' '.&mt('clicker file').' </td></tr>'."\n";
 7447: #
 7448: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 7449: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
 7450: #	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
 7451: #
 7452: #    if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
 7453: #	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
 7454: #	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
 7455: #	    ' '.&mt('receipt').': '.
 7456: #	    &Apache::lonnet::recprefix($env{'request.course.id'}).
 7457: #	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
 7458: #	    '</td></tr>'."\n";
 7459: #    } 
 7460: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 7461: #	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
 7462: #	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
 7463: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 7464: #	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
 7465: #	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
 7466: #
 7467: #    $result.='</table>'."\n".'</td>';
 7468:     $result.= '</tr></table>'."\n".
 7469: 	'</td></tr></table></form>'."\n";
 7470:     return $result;
 7471: }
 7472: 
 7473: sub reset_perm {
 7474:     undef(%perm);
 7475: }
 7476: 
 7477: sub init_perm {
 7478:     &reset_perm();
 7479:     foreach my $test_perm ('vgr','mgr','opa') {
 7480: 
 7481: 	my $scope = $env{'request.course.id'};
 7482: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 7483: 
 7484: 	    $scope .= '/'.$env{'request.course.sec'};
 7485: 	    if ( $perm{$test_perm}=
 7486: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 7487: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 7488: 	    } else {
 7489: 		delete($perm{$test_perm});
 7490: 	    }
 7491: 	}
 7492:     }
 7493: }
 7494: 
 7495: sub gather_clicker_ids {
 7496:     my %clicker_ids;
 7497: 
 7498:     my $classlist = &Apache::loncoursedata::get_classlist();
 7499: 
 7500:     # Set up a couple variables.
 7501:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 7502:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 7503:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 7504: 
 7505:     foreach my $student (keys(%$classlist)) {
 7506:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 7507:         my $username = $classlist->{$student}->[$username_idx];
 7508:         my $domain   = $classlist->{$student}->[$domain_idx];
 7509:         my $clickers =
 7510: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 7511:         foreach my $id (split(/\,/,$clickers)) {
 7512:             $id=~s/^[\#0]+//;
 7513:             $id=~s/[\-\:]//g;
 7514:             if (exists($clicker_ids{$id})) {
 7515: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 7516:             } else {
 7517: 		$clicker_ids{$id}=$username.':'.$domain;
 7518:             }
 7519:         }
 7520:     }
 7521:     return %clicker_ids;
 7522: }
 7523: 
 7524: sub gather_adv_clicker_ids {
 7525:     my %clicker_ids;
 7526:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 7527:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7528:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 7529:     foreach my $element (sort(keys(%coursepersonnel))) {
 7530:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 7531:             my ($puname,$pudom)=split(/\:/,$person);
 7532:             my $clickers =
 7533: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 7534:             foreach my $id (split(/\,/,$clickers)) {
 7535: 		$id=~s/^[\#0]+//;
 7536:                 $id=~s/[\-\:]//g;
 7537: 		if (exists($clicker_ids{$id})) {
 7538: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 7539: 		} else {
 7540: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 7541: 		}
 7542:             }
 7543:         }
 7544:     }
 7545:     return %clicker_ids;
 7546: }
 7547: 
 7548: sub clicker_grading_parameters {
 7549:     return ('gradingmechanism' => 'scalar',
 7550:             'upfiletype' => 'scalar',
 7551:             'specificid' => 'scalar',
 7552:             'pcorrect' => 'scalar',
 7553:             'pincorrect' => 'scalar');
 7554: }
 7555: 
 7556: sub process_clicker {
 7557:     my ($r)=@_;
 7558:     my ($symb)=&get_symb($r);
 7559:     if (!$symb) {return '';}
 7560:     my $result=&checkforfile_js();
 7561:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 7562:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 7563:     $result.=$table;
 7564:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 7565:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 7566:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
 7567:         '.</b></td></tr>'."\n";
 7568:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 7569: # Attempt to restore parameters from last session, set defaults if not present
 7570:     my %Saveable_Parameters=&clicker_grading_parameters();
 7571:     &Apache::loncommon::restore_course_settings('grades_clicker',
 7572:                                                  \%Saveable_Parameters);
 7573:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 7574:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 7575:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 7576:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 7577: 
 7578:     my %checked;
 7579:     foreach my $gradingmechanism ('attendance','personnel','specific') {
 7580:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 7581:           $checked{$gradingmechanism}="checked='checked'";
 7582:        }
 7583:     }
 7584: 
 7585:     my $upload=&mt("Upload File");
 7586:     my $type=&mt("Type");
 7587:     my $attendance=&mt("Award points just for participation");
 7588:     my $personnel=&mt("Correctness determined from response by course personnel");
 7589:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 7590:     my $pcorrect=&mt("Percentage points for correct solution");
 7591:     my $pincorrect=&mt("Percentage points for incorrect solution");
 7592:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 7593: 						   ('iclicker' => 'i>clicker',
 7594:                                                     'interwrite' => 'interwrite PRS'));
 7595:     $symb = &Apache::lonenc::check_encrypt($symb);
 7596:     $result.=<<ENDUPFORM;
 7597: <script type="text/javascript">
 7598: function sanitycheck() {
 7599: // Accept only integer percentages
 7600:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 7601:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 7602: // Find out grading choice
 7603:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 7604:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 7605:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 7606:       }
 7607:    }
 7608: // By default, new choice equals user selection
 7609:    newgradingchoice=gradingchoice;
 7610: // Not good to give more points for false answers than correct ones
 7611:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 7612:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 7613:    }
 7614: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 7615:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 7616:       document.forms.gradesupload.pcorrect.value=100;
 7617:       document.forms.gradesupload.pincorrect.value=100;
 7618:    }
 7619: // If the values are different, cannot be attendance only
 7620:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 7621:        (gradingchoice=='attendance')) {
 7622:        newgradingchoice='personnel';
 7623:    }
 7624: // Change grading choice to new one
 7625:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 7626:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 7627:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 7628:       } else {
 7629:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 7630:       }
 7631:    }
 7632: // Remember the old state
 7633:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 7634: }
 7635: </script>
 7636: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 7637: <input type="hidden" name="symb" value="$symb" />
 7638: <input type="hidden" name="command" value="processclickerfile" />
 7639: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 7640: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 7641: <input type="file" name="upfile" size="50" />
 7642: <br /><label>$type: $selectform</label>
 7643: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
 7644: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
 7645: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
 7646: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 7647: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 7648: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 7649: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 7650: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 7651: </form>
 7652: ENDUPFORM
 7653:     $result.='</td></tr></table>'."\n".
 7654:              '</td></tr></table><br /><br />'."\n";
 7655:     $result.=&show_grading_menu_form($symb);
 7656:     return $result;
 7657: }
 7658: 
 7659: sub process_clicker_file {
 7660:     my ($r)=@_;
 7661:     my ($symb)=&get_symb($r);
 7662:     if (!$symb) {return '';}
 7663: 
 7664:     my %Saveable_Parameters=&clicker_grading_parameters();
 7665:     &Apache::loncommon::store_course_settings('grades_clicker',
 7666:                                               \%Saveable_Parameters);
 7667: 
 7668:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 7669:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 7670: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 7671: 	return $result.&show_grading_menu_form($symb);
 7672:     }
 7673:     my %clicker_ids=&gather_clicker_ids();
 7674:     my %correct_ids;
 7675:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 7676: 	%correct_ids=&gather_adv_clicker_ids();
 7677:     }
 7678:     if ($env{'form.gradingmechanism'} eq 'specific') {
 7679: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 7680: 	   $correct_id=~tr/a-z/A-Z/;
 7681: 	   $correct_id=~s/\s//gs;
 7682: 	   $correct_id=~s/^[\#0]+//;
 7683:            $correct_id=~s/[\-\:]//g;
 7684:            if ($correct_id) {
 7685: 	      $correct_ids{$correct_id}='specified';
 7686:            }
 7687:         }
 7688:     }
 7689:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 7690: 	$result.=&mt('Score based on attendance only');
 7691:     } else {
 7692: 	my $number=0;
 7693: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 7694: 	foreach my $id (sort(keys(%correct_ids))) {
 7695: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 7696: 	    if ($correct_ids{$id} eq 'specified') {
 7697: 		$result.=&mt('specified');
 7698: 	    } else {
 7699: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 7700: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 7701: 	    }
 7702: 	    $number++;
 7703: 	}
 7704:         $result.="</p>\n";
 7705: 	if ($number==0) {
 7706: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 7707: 	    return $result.&show_grading_menu_form($symb);
 7708: 	}
 7709:     }
 7710:     if (length($env{'form.upfile'}) < 2) {
 7711:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 7712: 		     '<span class="LC_error">',
 7713: 		     '</span>',
 7714: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 7715:         return $result.&show_grading_menu_form($symb);
 7716:     }
 7717: 
 7718: # Were able to get all the info needed, now analyze the file
 7719: 
 7720:     $result.=&Apache::loncommon::studentbrowser_javascript();
 7721:     $symb = &Apache::lonenc::check_encrypt($symb);
 7722:     my $heading=&mt('Scanning clicker file');
 7723:     $result.=(<<ENDHEADER);
 7724: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 7725: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 7726: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 7727: <form method="post" action="/adm/grades" name="clickeranalysis">
 7728: <input type="hidden" name="symb" value="$symb" />
 7729: <input type="hidden" name="command" value="assignclickergrades" />
 7730: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 7731: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 7732: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 7733: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 7734: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 7735: ENDHEADER
 7736:     my %responses;
 7737:     my @questiontitles;
 7738:     my $errormsg='';
 7739:     my $number=0;
 7740:     if ($env{'form.upfiletype'} eq 'iclicker') {
 7741: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 7742:     }
 7743:     if ($env{'form.upfiletype'} eq 'interwrite') {
 7744:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 7745:     }
 7746:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 7747:              '<input type="hidden" name="number" value="'.$number.'" />'.
 7748:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
 7749:              '<input type="hidden" name="number" value="'.$number.'" />'.
 7750:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 7751:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 7752:              '<br />';
 7753: # Remember Question Titles
 7754: # FIXME: Possibly need delimiter other than ":"
 7755:     for (my $i=0;$i<$number;$i++) {
 7756:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 7757:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 7758:     }
 7759:     my $correct_count=0;
 7760:     my $student_count=0;
 7761:     my $unknown_count=0;
 7762: # Match answers with usernames
 7763: # FIXME: Possibly need delimiter other than ":"
 7764:     foreach my $id (keys(%responses)) {
 7765:        if ($correct_ids{$id}) {
 7766:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 7767:           $correct_count++;
 7768:        } elsif ($clicker_ids{$id}) {
 7769:           if ($clicker_ids{$id}=~/\,/) {
 7770: # More than one user with the same clicker!
 7771:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 7772:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 7773:                            "<select name='multi".$id."'>";
 7774:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 7775:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 7776:              }
 7777:              $result.='</select>';
 7778:              $unknown_count++;
 7779:           } else {
 7780: # Good: found one and only one user with the right clicker
 7781:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 7782:              $student_count++;
 7783:           }
 7784:        } else {
 7785:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 7786:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 7787:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 7788:                    "\n".&mt("Domain").": ".
 7789:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 7790:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 7791:           $unknown_count++;
 7792:        }
 7793:     }
 7794:     $result.='<hr />'.
 7795:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 7796:     if ($env{'form.gradingmechanism'} ne 'attendance') {
 7797:        if ($correct_count==0) {
 7798:           $errormsg.="Found no correct answers answers for grading!";
 7799:        } elsif ($correct_count>1) {
 7800:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 7801:        }
 7802:     }
 7803:     if ($number<1) {
 7804:        $errormsg.="Found no questions.";
 7805:     }
 7806:     if ($errormsg) {
 7807:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 7808:     } else {
 7809:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 7810:     }
 7811:     $result.='</form></td></tr></table>'."\n".
 7812:              '</td></tr></table><br /><br />'."\n";
 7813:     return $result.&show_grading_menu_form($symb);
 7814: }
 7815: 
 7816: sub iclicker_eval {
 7817:     my ($questiontitles,$responses)=@_;
 7818:     my $number=0;
 7819:     my $errormsg='';
 7820:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 7821:         my %components=&Apache::loncommon::record_sep($line);
 7822:         my @entries=map {$components{$_}} (sort(keys(%components)));
 7823: 	if ($entries[0] eq 'Question') {
 7824: 	    for (my $i=3;$i<$#entries;$i+=6) {
 7825: 		$$questiontitles[$number]=$entries[$i];
 7826: 		$number++;
 7827: 	    }
 7828: 	}
 7829: 	if ($entries[0]=~/^\#/) {
 7830: 	    my $id=$entries[0];
 7831: 	    my @idresponses;
 7832: 	    $id=~s/^[\#0]+//;
 7833: 	    for (my $i=0;$i<$number;$i++) {
 7834: 		my $idx=3+$i*6;
 7835: 		push(@idresponses,$entries[$idx]);
 7836: 	    }
 7837: 	    $$responses{$id}=join(',',@idresponses);
 7838: 	}
 7839:     }
 7840:     return ($errormsg,$number);
 7841: }
 7842: 
 7843: sub interwrite_eval {
 7844:     my ($questiontitles,$responses)=@_;
 7845:     my $number=0;
 7846:     my $errormsg='';
 7847:     my $skipline=1;
 7848:     my $questionnumber=0;
 7849:     my %idresponses=();
 7850:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 7851:         my %components=&Apache::loncommon::record_sep($line);
 7852:         my @entries=map {$components{$_}} (sort(keys(%components)));
 7853:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 7854:         if ($entries[1] eq 'Response') { $skipline=1; }
 7855:         next if $skipline;
 7856:         if ($entries[0]!=$questionnumber) {
 7857:            $questionnumber=$entries[0];
 7858:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 7859:            $number++;
 7860:         }
 7861:         my $id=$entries[4];
 7862:         $id=~s/^[\#0]+//;
 7863:         $id=~s/^v\d*\://i;
 7864:         $id=~s/[\-\:]//g;
 7865:         $idresponses{$id}[$number]=$entries[6];
 7866:     }
 7867:     foreach my $id (keys %idresponses) {
 7868:        $$responses{$id}=join(',',@{$idresponses{$id}});
 7869:        $$responses{$id}=~s/^\s*\,//;
 7870:     }
 7871:     return ($errormsg,$number);
 7872: }
 7873: 
 7874: sub assign_clicker_grades {
 7875:     my ($r)=@_;
 7876:     my ($symb)=&get_symb($r);
 7877:     if (!$symb) {return '';}
 7878: # See which part we are saving to
 7879:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 7880: # FIXME: This should probably look for the first handgradeable part
 7881:     my $part=$$partlist[0];
 7882: # Start screen output
 7883:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 7884: 
 7885:     my $heading=&mt('Assigning grades based on clicker file');
 7886:     $result.=(<<ENDHEADER);
 7887: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 7888: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 7889: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 7890: ENDHEADER
 7891: # Get correct result
 7892: # FIXME: Possibly need delimiter other than ":"
 7893:     my @correct=();
 7894:     my $gradingmechanism=$env{'form.gradingmechanism'};
 7895:     my $number=$env{'form.number'};
 7896:     if ($gradingmechanism ne 'attendance') {
 7897:        foreach my $key (keys(%env)) {
 7898:           if ($key=~/^form\.correct\:/) {
 7899:              my @input=split(/\,/,$env{$key});
 7900:              for (my $i=0;$i<=$#input;$i++) {
 7901:                  if (($correct[$i]) && ($input[$i]) &&
 7902:                      ($correct[$i] ne $input[$i])) {
 7903:                     $result.='<br /><span class="LC_warning">'.
 7904:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 7905:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 7906:                  } elsif ($input[$i]) {
 7907:                     $correct[$i]=$input[$i];
 7908:                  }
 7909:              }
 7910:           }
 7911:        }
 7912:        for (my $i=0;$i<$number;$i++) {
 7913:           if (!$correct[$i]) {
 7914:              $result.='<br /><span class="LC_error">'.
 7915:                       &mt('No correct result given for question "[_1]"!',
 7916:                           $env{'form.question:'.$i}).'</span>';
 7917:           }
 7918:        }
 7919:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 7920:     }
 7921: # Start grading
 7922:     my $pcorrect=$env{'form.pcorrect'};
 7923:     my $pincorrect=$env{'form.pincorrect'};
 7924:     my $storecount=0;
 7925:     foreach my $key (keys(%env)) {
 7926:        my $user='';
 7927:        if ($key=~/^form\.student\:(.*)$/) {
 7928:           $user=$1;
 7929:        }
 7930:        if ($key=~/^form\.unknown\:(.*)$/) {
 7931:           my $id=$1;
 7932:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 7933:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 7934:           } elsif ($env{'form.multi'.$id}) {
 7935:              $user=$env{'form.multi'.$id};
 7936:           }
 7937:        }
 7938:        if ($user) { 
 7939:           my @answer=split(/\,/,$env{$key});
 7940:           my $sum=0;
 7941:           for (my $i=0;$i<$number;$i++) {
 7942:              if ($answer[$i]) {
 7943:                 if ($gradingmechanism eq 'attendance') {
 7944:                    $sum+=$pcorrect;
 7945:                 } else {
 7946:                    if ($answer[$i] eq $correct[$i]) {
 7947:                       $sum+=$pcorrect;
 7948:                    } else {
 7949:                       $sum+=$pincorrect;
 7950:                    }
 7951:                 }
 7952:              }
 7953:           }
 7954:           my $ave=$sum/(100*$number);
 7955: # Store
 7956:           my ($username,$domain)=split(/\:/,$user);
 7957:           my %grades=();
 7958:           $grades{"resource.$part.solved"}='correct_by_override';
 7959:           $grades{"resource.$part.awarded"}=$ave;
 7960:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 7961:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 7962:                                                  $env{'request.course.id'},
 7963:                                                  $domain,$username);
 7964:           if ($returncode ne 'ok') {
 7965:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 7966:           } else {
 7967:              $storecount++;
 7968:           }
 7969:        }
 7970:     }
 7971: # We are done
 7972:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
 7973:              '</td></tr></table>'."\n".
 7974:              '</td></tr></table><br /><br />'."\n";
 7975:     return $result.&show_grading_menu_form($symb);
 7976: }
 7977: 
 7978: sub handler {
 7979:     my $request=$_[0];
 7980:     &reset_caches();
 7981:     if ($env{'browser.mathml'}) {
 7982: 	&Apache::loncommon::content_type($request,'text/xml');
 7983:     } else {
 7984: 	&Apache::loncommon::content_type($request,'text/html');
 7985:     }
 7986:     $request->send_http_header;
 7987:     return '' if $request->header_only;
 7988:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 7989:     my $symb=&get_symb($request,1);
 7990:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 7991:     my $command=$commands[0];
 7992: 
 7993:     if ($#commands > 0) {
 7994: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 7995:     }
 7996: 
 7997: 
 7998:     $request->print(&Apache::loncommon::start_page('Grading'));
 7999:     if ($symb eq '' && $command eq '') {
 8000: 	if ($env{'user.adv'}) {
 8001: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 8002: 		($env{'form.codethree'})) {
 8003: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 8004: 		    $env{'form.codethree'};
 8005: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 8006: 		    &Apache::lonnet::checkin($token);
 8007: 		if ($tsymb) {
 8008: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 8009: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 8010: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
 8011: 					  ('grade_username' => $tuname,
 8012: 					   'grade_domain' => $tudom,
 8013: 					   'grade_courseid' => $tcrsid,
 8014: 					   'grade_symb' => $tsymb)));
 8015: 		    } else {
 8016: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 8017: 		    }
 8018: 		} else {
 8019: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 8020: 		}
 8021: 	    } else {
 8022: 		$request->print(&Apache::lonxml::tokeninputfield());
 8023: 	    }
 8024: 	}
 8025:     } else {
 8026: 	&init_perm();
 8027: 	if ($command eq 'submission' && $perm{'vgr'}) {
 8028: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 8029: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 8030: 	    &pickStudentPage($request);
 8031: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 8032: 	    &displayPage($request);
 8033: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 8034: 	    &updateGradeByPage($request);
 8035: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 8036: 	    &processGroup($request);
 8037: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 8038: 	    $request->print(&grading_menu($request));
 8039: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 8040: 	    $request->print(&submit_options($request));
 8041: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 8042: 	    $request->print(&viewgrades($request));
 8043: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 8044: 	    $request->print(&processHandGrade($request));
 8045: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 8046: 	    $request->print(&editgrades($request));
 8047: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 8048: 	    $request->print(&verifyreceipt($request));
 8049:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 8050:             $request->print(&process_clicker($request));
 8051:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 8052:             $request->print(&process_clicker_file($request));
 8053:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 8054:             $request->print(&assign_clicker_grades($request));
 8055: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 8056: 	    $request->print(&upcsvScores_form($request));
 8057: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 8058: 	    $request->print(&csvupload($request));
 8059: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 8060: 	    $request->print(&csvuploadmap($request));
 8061: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 8062: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 8063: 		$request->print(&csvuploadoptions($request));
 8064: 	    } else {
 8065: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 8066: 		    $env{'form.upfile_associate'} = 'reverse';
 8067: 		} else {
 8068: 		    $env{'form.upfile_associate'} = 'forward';
 8069: 		}
 8070: 		$request->print(&csvuploadmap($request));
 8071: 	    }
 8072: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 8073: 	    $request->print(&csvuploadassign($request));
 8074: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 8075: 	    $request->print(&scantron_selectphase($request));
 8076:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 8077:  	    $request->print(&scantron_do_warning($request));
 8078: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 8079: 	    $request->print(&scantron_validate_file($request));
 8080: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 8081: 	    $request->print(&scantron_process_students($request));
 8082:  	} elsif ($command eq 'scantronupload' && 
 8083:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 8084: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 8085:  	    $request->print(&scantron_upload_scantron_data($request)); 
 8086:  	} elsif ($command eq 'scantronupload_save' &&
 8087:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 8088: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 8089:  	    $request->print(&scantron_upload_scantron_data_save($request));
 8090:  	} elsif ($command eq 'scantron_download' &&
 8091: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 8092:  	    $request->print(&scantron_download_scantron_data($request));
 8093: 	} elsif ($command) {
 8094: 	    $request->print("Access Denied ($command)");
 8095: 	}
 8096:     }
 8097:     $request->print(&Apache::loncommon::end_page());
 8098:     &reset_caches();
 8099:     return '';
 8100: }
 8101: 
 8102: 1;
 8103: 
 8104: __END__;

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