File:  [LON-CAPA] / loncom / homework / grades.pm
Revision 1.447: download - view: text, annotated - select for diffs
Tue Oct 9 09:16:04 2007 UTC (16 years, 6 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Removed >my< log spew too, .. saving work on BZ 4074 not yet done..
resolved conflict with banghart's last commit.

    1: # The LearningOnline Network with CAPA
    2: # The LON-CAPA Grading handler
    3: #
    4: # $Id: grades.pm,v 1.447 2007/10/09 09:16:04 foxr Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::grades;
   30: use strict;
   31: use Apache::style;
   32: use Apache::lonxml;
   33: use Apache::lonnet;
   34: use Apache::loncommon;
   35: use Apache::lonhtmlcommon;
   36: use Apache::lonnavmaps;
   37: use Apache::lonhomework;
   38: use Apache::loncoursedata;
   39: use Apache::lonmsg();
   40: use Apache::Constants qw(:common);
   41: use Apache::lonlocal;
   42: use Apache::lonenc;
   43: use String::Similarity;
   44: use LONCAPA;
   45: 
   46: use POSIX qw(floor);
   47: 
   48: 
   49: my %perm=();
   50: my %bubble_lines_per_response = ();     # no. bubble lines for each response.
   51:                                    # index is "symb.part_id"
   52: 
   53: my %first_bubble_line = ();	# First bubble line no. for each bubble.
   54: 
   55: # Save and restore the bubble lines array to the form env.
   56: 
   57: 
   58: sub save_bubble_lines {
   59: 
   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:     my $bubble_line = $first_bubble_line{$response};
   88:     my $bubble_lines= $bubble_linse_per_response{$response};
   89:     my $selected = "";
   90: 
   91:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
   92: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"};
   93: 	$bubble_line++;
   94:     }
   95:     return $selected;
   96: }
   97: 
   98: 
   99: # ----- These first few routines are general use routines.----
  100: 
  101: # Return the number of occurences of a pattern in a string.
  102: 
  103: sub occurence_count {
  104:     my ($string, $pattern) = @_;
  105: 
  106:     my @matches = ($string =~ /$pattern/g);
  107: 
  108:     return scalar(@matches);
  109: }
  110: 
  111: 
  112: # Take a string known to have digits and convert all the
  113: # digits into letters in the range J,A..I.
  114: 
  115: sub digits_to_letters {
  116:     my ($input) = @_;
  117: 
  118:     my @alphabet = ('J', 'A'..'I');
  119: 
  120:     my @input    = split(//, $input);
  121:     my $output ='';
  122:     for (my $i = 0; $i < scalar(@input); $i++) {
  123: 	if ($input[$i] =~ /\d/) {
  124: 	    $output .= $alphabet[$input[$i]];
  125: 	} else {
  126: 	    $output .= $input[$i];
  127: 	}
  128:     }
  129:     return $output;
  130: }
  131: 
  132: #
  133: # --- Retrieve the parts from the metadata file.---
  134: sub getpartlist {
  135:     my ($symb) = @_;
  136: 
  137:     my $navmap   = Apache::lonnavmaps::navmap->new();
  138:     my $res      = $navmap->getBySymb($symb);
  139:     my $partlist = $res->parts();
  140:     my $url      = $res->src();
  141:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
  142: 
  143:     my @stores;
  144:     foreach my $part (@{ $partlist }) {
  145: 	foreach my $key (@metakeys) {
  146: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
  147: 	}
  148:     }
  149:     return @stores;
  150: }
  151: 
  152: # --- Get the symbolic name of a problem and the url
  153: sub get_symb {
  154:     my ($request,$silent) = @_;
  155:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
  156:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
  157:     if ($symb eq '') { 
  158: 	if (!$silent) {
  159: 	    $request->print("Unable to handle ambiguous references:$url:.");
  160: 	    return ();
  161: 	}
  162:     }
  163:     &Apache::lonenc::check_decrypt(\$symb);
  164:     return ($symb);
  165: }
  166: 
  167: #--- Format fullname, username:domain if different for display
  168: #--- Use anywhere where the student names are listed
  169: sub nameUserString {
  170:     my ($type,$fullname,$uname,$udom) = @_;
  171:     if ($type eq 'header') {
  172: 	return '<b>&nbsp;Fullname&nbsp;</b><span class="LC_internal_info">(Username)</span>';
  173:     } else {
  174: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
  175: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
  176:     }
  177: }
  178: 
  179: #--- Get the partlist and the response type for a given problem. ---
  180: #--- Indicate if a response type is coded handgraded or not. ---
  181: sub response_type {
  182:     my ($symb) = shift;
  183: 
  184:     my $navmap = Apache::lonnavmaps::navmap->new();
  185:     my $res = $navmap->getBySymb($symb);
  186:     my $partlist = $res->parts();
  187:     my %vPart = 
  188: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
  189:     my (%response_types,%handgrade);
  190:     foreach my $part (@{ $partlist }) {
  191: 	next if (%vPart && !exists($vPart{$part}));
  192: 
  193: 	my @types = $res->responseType($part);
  194: 	my @ids = $res->responseIds($part);
  195: 	for (my $i=0; $i < scalar(@ids); $i++) {
  196: 	    $response_types{$part}{$ids[$i]} = $types[$i];
  197: 	    $handgrade{$part.'_'.$ids[$i]} = 
  198: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
  199: 				     '.handgrade',$symb);
  200: 	}
  201:     }
  202:     return ($partlist,\%handgrade,\%response_types);
  203: }
  204: 
  205: sub flatten_responseType {
  206:     my ($responseType) = @_;
  207:     my @part_response_id =
  208: 	map { 
  209: 	    my $part = $_;
  210: 	    map {
  211: 		[$part,$_]
  212: 		} sort(keys(%{ $responseType->{$part} }));
  213: 	} sort(keys(%$responseType));
  214:     return @part_response_id;
  215: }
  216: 
  217: sub get_display_part {
  218:     my ($partID,$symb)=@_;
  219:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
  220:     if (defined($display) and $display ne '') {
  221: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
  222:     } else {
  223: 	$display=$partID;
  224:     }
  225:     return $display;
  226: }
  227: 
  228: #--- Show resource title
  229: #--- and parts and response type
  230: sub showResourceInfo {
  231:     my ($symb,$probTitle,$checkboxes) = @_;
  232:     my $col=3;
  233:     if ($checkboxes) { $col=4; }
  234:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
  235:     $result .='<table border="0">';
  236:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
  237:     my %resptype = ();
  238:     my $hdgrade='no';
  239:     my %partsseen;
  240:     foreach my $partID (sort keys(%$responseType)) {
  241: 	foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
  242: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
  243: 	    my $responsetype = $responseType->{$partID}->{$resID};
  244: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
  245: 	    $result.='<tr>';
  246: 	    if ($checkboxes) {
  247: 		if (exists($partsseen{$partID})) {
  248: 		    $result.="<td>&nbsp;</td>";
  249: 		} else {
  250: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
  251: 		}
  252: 		$partsseen{$partID}=1;
  253: 	    }
  254: 	    my $display_part=&get_display_part($partID,$symb);
  255: 	    $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
  256: 		$resID.'</span></td>'.
  257: 		'<td><b>Type: </b>'.$responsetype.'</td></tr>';
  258: #	    '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
  259: 	}
  260:     }
  261:     $result.='</table>'."\n";
  262:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
  263: }
  264: 
  265: sub reset_caches {
  266:     &reset_analyze_cache();
  267:     &reset_perm();
  268: }
  269: 
  270: {
  271:     my %analyze_cache;
  272: 
  273:     sub reset_analyze_cache {
  274: 	undef(%analyze_cache);
  275:     }
  276: 
  277:     sub get_analyze {
  278: 	my ($symb,$uname,$udom)=@_;
  279: 	my $key = "$symb\0$uname\0$udom";
  280: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
  281: 
  282: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
  283: 	$url=&Apache::lonnet::clutter($url);
  284: 	my $subresult=&Apache::lonnet::ssi($url,
  285: 					   ('grade_target' => 'analyze'),
  286: 					   ('grade_domain' => $udom),
  287: 					   ('grade_symb' => $symb),
  288: 					   ('grade_courseid' => 
  289: 					    $env{'request.course.id'}),
  290: 					   ('grade_username' => $uname));
  291: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
  292: 	my %analyze=&Apache::lonnet::str2hash($subresult);
  293: 	return $analyze_cache{$key} = \%analyze;
  294:     }
  295: 
  296:     sub get_order {
  297: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  298: 	my $analyze = &get_analyze($symb,$uname,$udom);
  299: 	return $analyze->{"$partid.$respid.shown"};
  300:     }
  301: 
  302:     sub get_radiobutton_correct_foil {
  303: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
  304: 	my $analyze = &get_analyze($symb,$uname,$udom);
  305: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
  306: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
  307: 		return $foil;
  308: 	    }
  309: 	}
  310:     }
  311: }
  312: 
  313: #--- Clean response type for display
  314: #--- Currently filters option/rank/radiobutton/match/essay/Task
  315: #        response types only.
  316: sub cleanRecord {
  317:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
  318: 	$uname,$udom) = @_;
  319:     my $grayFont = '<span class="LC_internal_info">';
  320:     if ($response =~ /^(option|rank)$/) {
  321: 	my %answer=&Apache::lonnet::str2hash($answer);
  322: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  323: 	my ($toprow,$bottomrow);
  324: 	foreach my $foil (@$order) {
  325: 	    if ($grading{$foil} == 1) {
  326: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
  327: 	    } else {
  328: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
  329: 	    }
  330: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  331: 	}
  332: 	return '<blockquote><table border="1">'.
  333: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
  334: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
  335: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  336:     } elsif ($response eq 'match') {
  337: 	my %answer=&Apache::lonnet::str2hash($answer);
  338: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
  339: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
  340: 	my ($toprow,$middlerow,$bottomrow);
  341: 	foreach my $foil (@$order) {
  342: 	    my $item=shift(@items);
  343: 	    if ($grading{$foil} == 1) {
  344: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
  345: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
  346: 	    } else {
  347: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
  348: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
  349: 	    }
  350: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  351: 	}
  352: 	return '<blockquote><table border="1">'.
  353: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
  354: 	    '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
  355: 	    $middlerow.'</tr>'.
  356: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
  357: 	    $bottomrow.'</tr>'.'</table></blockquote>';
  358:     } elsif ($response eq 'radiobutton') {
  359: 	my %answer=&Apache::lonnet::str2hash($answer);
  360: 	my ($toprow,$bottomrow);
  361: 	my $correct = 
  362: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
  363: 	foreach my $foil (@$order) {
  364: 	    if (exists($answer{$foil})) {
  365: 		if ($foil eq $correct) {
  366: 		    $toprow.='<td><b>true</b></td>';
  367: 		} else {
  368: 		    $toprow.='<td><i>true</i></td>';
  369: 		}
  370: 	    } else {
  371: 		$toprow.='<td>false</td>';
  372: 	    }
  373: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
  374: 	}
  375: 	return '<blockquote><table border="1">'.
  376: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
  377: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
  378: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
  379:     } elsif ($response eq 'essay') {
  380: 	if (! exists ($env{'form.'.$symb})) {
  381: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
  382: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
  383: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
  384: 
  385: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
  386: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
  387: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
  388: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
  389: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
  390: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
  391: 	}
  392: 	$answer =~ s-\n-<br />-g;
  393: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
  394:     } elsif ( $response eq 'organic') {
  395: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
  396: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
  397: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
  398: 	return $result;
  399:     } elsif ( $response eq 'Task') {
  400: 	if ( $answer eq 'SUBMITTED') {
  401: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
  402: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
  403: 	    return $result;
  404: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
  405: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
  406: 			       keys(%{$record}));
  407: 	    return join('<br />',($version,@matches));
  408: 			       
  409: 			       
  410: 	} else {
  411: 	    my $result =
  412: 		'<p>'
  413: 		.&mt('Overall result: [_1]',
  414: 		     $record->{$version."resource.$respid.$partid.status"})
  415: 		.'</p>';
  416: 	    
  417: 	    $result .= '<ul>';
  418: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
  419: 			     keys(%{$record}));
  420: 	    foreach my $grade (sort(@grade)) {
  421: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
  422: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
  423: 				     $dim, $record->{$grade}).
  424: 			  '</li>';
  425: 	    }
  426: 	    $result.='</ul>';
  427: 	    return $result;
  428: 	}
  429:     } elsif ( $response =~ m/(?:numerical|formula)/) {
  430: 	$answer = 
  431: 	    &Apache::loncommon::format_previous_attempt_value('submission',
  432: 							      $answer);
  433:     }
  434:     return $answer;
  435: }
  436: 
  437: #-- A couple of common js functions
  438: sub commonJSfunctions {
  439:     my $request = shift;
  440:     $request->print(<<COMMONJSFUNCTIONS);
  441: <script type="text/javascript" language="javascript">
  442:     function radioSelection(radioButton) {
  443: 	var selection=null;
  444: 	if (radioButton.length > 1) {
  445: 	    for (var i=0; i<radioButton.length; i++) {
  446: 		if (radioButton[i].checked) {
  447: 		    return radioButton[i].value;
  448: 		}
  449: 	    }
  450: 	} else {
  451: 	    if (radioButton.checked) return radioButton.value;
  452: 	}
  453: 	return selection;
  454:     }
  455: 
  456:     function pullDownSelection(selectOne) {
  457: 	var selection="";
  458: 	if (selectOne.length > 1) {
  459: 	    for (var i=0; i<selectOne.length; i++) {
  460: 		if (selectOne[i].selected) {
  461: 		    return selectOne[i].value;
  462: 		}
  463: 	    }
  464: 	} else {
  465:             // only one value it must be the selected one
  466: 	    return selectOne.value;
  467: 	}
  468:     }
  469: </script>
  470: COMMONJSFUNCTIONS
  471: }
  472: 
  473: #--- Dumps the class list with usernames,list of sections,
  474: #--- section, ids and fullnames for each user.
  475: sub getclasslist {
  476:     my ($getsec,$filterlist) = @_;
  477:     my @getsec;
  478:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  479:     if (!ref($getsec)) {
  480: 	if ($getsec ne '' && $getsec ne 'all') {
  481: 	    @getsec=($getsec);
  482: 	}
  483:     } else {
  484: 	@getsec=@{$getsec};
  485:     }
  486:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
  487: 
  488:     my $classlist=&Apache::loncoursedata::get_classlist();
  489:     # Bail out if we were unable to get the classlist
  490:     return if (! defined($classlist));
  491:     #
  492:     my %sections;
  493:     my %fullnames;
  494:     foreach my $student (keys(%$classlist)) {
  495:         my $end      = 
  496:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
  497:         my $start    = 
  498:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
  499:         my $id       = 
  500:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
  501:         my $section  = 
  502:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  503:         my $fullname = 
  504:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
  505:         my $status   = 
  506:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
  507: 	# filter students according to status selected
  508: 	if ($filterlist && (!($stu_status =~ /Any/))) {
  509: 	    if (!($stu_status =~ $status)) {
  510: 		delete ($classlist->{$student});
  511: 		next;
  512: 	    }
  513: 	}
  514: 	$section = ($section ne '' ? $section : 'none');
  515: 	if (&canview($section)) {
  516: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
  517: 		$sections{$section}++;
  518: 		$fullnames{$student}=$fullname;
  519: 	    } else {
  520: 		delete($classlist->{$student});
  521: 	    }
  522: 	} else {
  523: 	    delete($classlist->{$student});
  524: 	}
  525:     }
  526:     my %seen = ();
  527:     my @sections = sort(keys(%sections));
  528:     return ($classlist,\@sections,\%fullnames);
  529: }
  530: 
  531: sub canmodify {
  532:     my ($sec)=@_;
  533:     if ($perm{'mgr'}) {
  534: 	if (!defined($perm{'mgr_section'})) {
  535: 	    # can modify whole class
  536: 	    return 1;
  537: 	} else {
  538: 	    if ($sec eq $perm{'mgr_section'}) {
  539: 		#can modify the requested section
  540: 		return 1;
  541: 	    } else {
  542: 		# can't modify the request section
  543: 		return 0;
  544: 	    }
  545: 	}
  546:     }
  547:     #can't modify
  548:     return 0;
  549: }
  550: 
  551: sub canview {
  552:     my ($sec)=@_;
  553:     if ($perm{'vgr'}) {
  554: 	if (!defined($perm{'vgr_section'})) {
  555: 	    # can modify whole class
  556: 	    return 1;
  557: 	} else {
  558: 	    if ($sec eq $perm{'vgr_section'}) {
  559: 		#can modify the requested section
  560: 		return 1;
  561: 	    } else {
  562: 		# can't modify the request section
  563: 		return 0;
  564: 	    }
  565: 	}
  566:     }
  567:     #can't modify
  568:     return 0;
  569: }
  570: 
  571: #--- Retrieve the grade status of a student for all the parts
  572: sub student_gradeStatus {
  573:     my ($symb,$udom,$uname,$partlist) = @_;
  574:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
  575:     my %partstatus = ();
  576:     foreach (@$partlist) {
  577: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
  578: 	$status              = 'nothing' if ($status eq '');
  579: 	$partstatus{$_}      = $status;
  580: 	my $subkey           = "resource.$_.submitted_by";
  581: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
  582:     }
  583:     return %partstatus;
  584: }
  585: 
  586: # hidden form and javascript that calls the form
  587: # Use by verifyscript and viewgrades
  588: # Shows a student's view of problem and submission
  589: sub jscriptNform {
  590:     my ($symb) = @_;
  591:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  592:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
  593: 	'    function viewOneStudent(user,domain) {'."\n".
  594: 	'	document.onestudent.student.value = user;'."\n".
  595: 	'	document.onestudent.userdom.value = domain;'."\n".
  596: 	'	document.onestudent.submit();'."\n".
  597: 	'    }'."\n".
  598: 	'</script>'."\n";
  599:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
  600: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  601: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
  602: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
  603: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
  604: 	'<input type="hidden" name="command" value="submission" />'."\n".
  605: 	'<input type="hidden" name="student" value="" />'."\n".
  606: 	'<input type="hidden" name="userdom" value="" />'."\n".
  607: 	'</form>'."\n";
  608:     return $jscript;
  609: }
  610: 
  611: 
  612: 
  613: # Given the score (as a number [0-1] and the weight) what is the final
  614: # point value? This function will round to the nearest tenth, third,
  615: # or quarter if one of those is within the tolerance of .00001.
  616: sub compute_points {
  617:     my ($score, $weight) = @_;
  618:     
  619:     my $tolerance = .00001;
  620:     my $points = $score * $weight;
  621: 
  622:     # Check for nearness to 1/x.
  623:     my $check_for_nearness = sub {
  624:         my ($factor) = @_;
  625:         my $num = ($points * $factor) + $tolerance;
  626:         my $floored_num = floor($num);
  627:         if ($num - $floored_num < 2 * $tolerance * $factor) {
  628:             return $floored_num / $factor;
  629:         }
  630:         return $points;
  631:     };
  632: 
  633:     $points = $check_for_nearness->(10);
  634:     $points = $check_for_nearness->(3);
  635:     $points = $check_for_nearness->(4);
  636:     
  637:     return $points;
  638: }
  639: 
  640: #------------------ End of general use routines --------------------
  641: 
  642: #
  643: # Find most similar essay
  644: #
  645: 
  646: sub most_similar {
  647:     my ($uname,$udom,$uessay,$old_essays)=@_;
  648: 
  649: # ignore spaces and punctuation
  650: 
  651:     $uessay=~s/\W+/ /gs;
  652: 
  653: # ignore empty submissions (occuring when only files are sent)
  654: 
  655:     unless ($uessay=~/\w+/) { return ''; }
  656: 
  657: # these will be returned. Do not care if not at least 50 percent similar
  658:     my $limit=0.6;
  659:     my $sname='';
  660:     my $sdom='';
  661:     my $scrsid='';
  662:     my $sessay='';
  663: # go through all essays ...
  664:     foreach my $tkey (keys(%$old_essays)) {
  665: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
  666: # ... except the same student
  667:         next if (($tname eq $uname) && ($tdom eq $udom));
  668: 	my $tessay=$old_essays->{$tkey};
  669: 	$tessay=~s/\W+/ /gs;
  670: # String similarity gives up if not even limit
  671: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
  672: # Found one
  673: 	if ($tsimilar>$limit) {
  674: 	    $limit=$tsimilar;
  675: 	    $sname=$tname;
  676: 	    $sdom=$tdom;
  677: 	    $scrsid=$tcrsid;
  678: 	    $sessay=$old_essays->{$tkey};
  679: 	}
  680:     }
  681:     if ($limit>0.6) {
  682:        return ($sname,$sdom,$scrsid,$sessay,$limit);
  683:     } else {
  684:        return ('','','','',0);
  685:     }
  686: }
  687: 
  688: #-------------------------------------------------------------------
  689: 
  690: #------------------------------------ Receipt Verification Routines
  691: #
  692: #--- Check whether a receipt number is valid.---
  693: sub verifyreceipt {
  694:     my $request  = shift;
  695: 
  696:     my $courseid = $env{'request.course.id'};
  697:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
  698: 	$env{'form.receipt'};
  699:     $receipt     =~ s/[^\-\d]//g;
  700:     my ($symb)   = &get_symb($request);
  701: 
  702:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
  703: 	$receipt.'</h3></span>'."\n".
  704: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
  705: 
  706:     my ($string,$contents,$matches) = ('','',0);
  707:     my (undef,undef,$fullname) = &getclasslist('all','0');
  708:     
  709:     my $receiptparts=0;
  710:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
  711: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
  712:     my $parts=['0'];
  713:     if ($receiptparts) { ($parts)=&response_type($symb); }
  714:     foreach (sort 
  715: 	     {
  716: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  717: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  718: 		 }
  719: 		 return $a cmp $b;
  720: 	     } (keys(%$fullname))) {
  721: 	my ($uname,$udom)=split(/\:/);
  722: 	foreach my $part (@$parts) {
  723: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
  724: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
  725: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
  726: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
  727: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
  728: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
  729: 		if ($receiptparts) {
  730: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
  731: 		}
  732: 		$contents.='</tr>'."\n";
  733: 		
  734: 		$matches++;
  735: 	    }
  736: 	}
  737:     }
  738:     if ($matches == 0) {
  739: 	$string = $title.'No match found for the above receipt.';
  740:     } else {
  741: 	$string = &jscriptNform($symb).$title.
  742: 	    'The above receipt matches the following student'.
  743: 	    ($matches <= 1 ? '.' : 's.')."\n".
  744: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
  745: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
  746: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
  747: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
  748: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
  749: 	if ($receiptparts) {
  750: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
  751: 	}
  752: 	$string.='</tr>'."\n".$contents.
  753: 	    '</table></td></tr></table>'."\n";
  754:     }
  755:     return $string.&show_grading_menu_form($symb);
  756: }
  757: 
  758: #--- This is called by a number of programs.
  759: #--- Called from the Grading Menu - View/Grade an individual student
  760: #--- Also called directly when one clicks on the subm button 
  761: #    on the problem page.
  762: sub listStudents {
  763:     my ($request) = shift;
  764: 
  765:     my ($symb) = &get_symb($request);
  766:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
  767:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
  768:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
  769:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
  770: 
  771:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
  772:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
  773: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
  774: 
  775:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
  776: 	' Submissions for a Student or a Group of Students</span></h3>';
  777: 
  778:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
  779: 
  780:     $request->print(<<LISTJAVASCRIPT);
  781: <script type="text/javascript" language="javascript">
  782:     function checkSelect(checkBox) {
  783: 	var ctr=0;
  784: 	var sense="";
  785: 	if (checkBox.length > 1) {
  786: 	    for (var i=0; i<checkBox.length; i++) {
  787: 		if (checkBox[i].checked) {
  788: 		    ctr++;
  789: 		}
  790: 	    }
  791: 	    sense = "a student or group of students";
  792: 	} else {
  793: 	    if (checkBox.checked) {
  794: 		ctr = 1;
  795: 	    }
  796: 	    sense = "the student";
  797: 	}
  798: 	if (ctr == 0) {
  799: 	    alert("Please select "+sense+" before clicking on the Next button.");
  800: 	    return false;
  801: 	}
  802: 	document.gradesub.submit();
  803:     }
  804: 
  805:     function reLoadList(formname) {
  806: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
  807: 	formname.command.value = 'submission';
  808: 	formname.submit();
  809:     }
  810: </script>
  811: LISTJAVASCRIPT
  812: 
  813:     &commonJSfunctions($request);
  814:     $request->print($result);
  815: 
  816:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
  817:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
  818:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
  819: 	"\n".$table.
  820: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
  821: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
  822: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
  823: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
  824: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
  825: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
  826: 	'&nbsp;<b>Submissions: </b>'."\n";
  827:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
  828: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
  829:     }
  830:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
  831:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
  832:     $env{'form.Status'} = $saveStatus;
  833:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
  834: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
  835: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
  836: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
  837:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
  838:         '<option value="1">Whole Points</option>'.
  839:         '<option value=".5">Half Points</option>'.
  840:         '<option value=".25">Quarter Points</option>'.
  841:         '<option value=".1">Tenths of a Point</option>'.
  842:         '</select>'.
  843:         &build_section_inputs().
  844: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
  845: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
  846: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
  847: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
  848: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
  849: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
  850: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
  851: 
  852:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
  853: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
  854:     } else {
  855: 	$gradeTable.='<b>Student Status:</b> '.
  856: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
  857:     }
  858: 
  859:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
  860: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
  861: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
  862: 
  863: # checkall buttons
  864:     $gradeTable.=&check_script('gradesub', 'stuinfo');
  865:     $gradeTable.='<input type="button" '."\n".
  866: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
  867: 	'value="Next->" /> <br />'."\n";
  868:     $gradeTable.=&check_buttons();
  869:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
  870:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
  871:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
  872: 	'<table border="0"><tr bgcolor="#e6ffff">';
  873:     my $loop = 0;
  874:     while ($loop < 2) {
  875: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
  876: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
  877: 	if ($env{'form.showgrading'} eq 'yes' 
  878: 	    && $submitonly ne 'queued'
  879: 	    && $submitonly ne 'all') {
  880: 	    foreach (sort(@$partlist)) {
  881: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
  882: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
  883: 		    ' Status&nbsp;</b></td>';
  884: 	    }
  885: 	} elsif ($submitonly eq 'queued') {
  886: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
  887: 	}
  888: 	$loop++;
  889: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
  890:     }
  891:     $gradeTable.='</tr>'."\n";
  892: 
  893:     my $ctr = 0;
  894:     foreach my $student (sort 
  895: 			 {
  896: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
  897: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
  898: 			     }
  899: 			     return $a cmp $b;
  900: 			 }
  901: 			 (keys(%$fullname))) {
  902: 	my ($uname,$udom) = split(/:/,$student);
  903: 
  904: 	my %status = ();
  905: 
  906: 	if ($submitonly eq 'queued') {
  907: 	    my %queue_status = 
  908: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
  909: 							$udom,$uname);
  910: 	    next if (!defined($queue_status{'gradingqueue'}));
  911: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
  912: 	}
  913: 
  914: 	if ($env{'form.showgrading'} eq 'yes' 
  915: 	    && $submitonly ne 'queued'
  916: 	    && $submitonly ne 'all') {
  917: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
  918: 	    my $submitted = 0;
  919: 	    my $graded = 0;
  920: 	    my $incorrect = 0;
  921: 	    foreach (keys(%status)) {
  922: 		$submitted = 1 if ($status{$_} ne 'nothing');
  923: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
  924: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
  925: 		
  926: 		my ($foo,$partid,$foo1) = split(/\./,$_);
  927: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
  928: 		    $submitted = 0;
  929: 		    my ($part)=split(/\./,$partid);
  930: 		    $gradeTable.='<input type="hidden" name="'.
  931: 			$student.':'.$part.':submitted_by" value="'.
  932: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
  933: 		}
  934: 	    }
  935: 	    
  936: 	    next if (!$submitted && ($submitonly eq 'yes' ||
  937: 				     $submitonly eq 'incorrect' ||
  938: 				     $submitonly eq 'graded'));
  939: 	    next if (!$graded && ($submitonly eq 'graded'));
  940: 	    next if (!$incorrect && $submitonly eq 'incorrect');
  941: 	}
  942: 
  943: 	$ctr++;
  944: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
  945: 
  946: 	if ( $perm{'vgr'} eq 'F' ) {
  947: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
  948: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
  949:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
  950:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
  951: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
  952: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
  953: 	       '&nbsp;'.$section.'</td>'."\n";
  954: 
  955: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
  956: 		foreach (sort keys(%status)) {
  957: 		    next if (/^resource.*?submitted_by$/);
  958: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
  959: 		}
  960: 	    }
  961: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
  962: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
  963: 	}
  964:     }
  965:     if ($ctr%2 ==1) {
  966: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
  967: 	    if ($env{'form.showgrading'} eq 'yes' 
  968: 		&& $submitonly ne 'queued'
  969: 		&& $submitonly ne 'all') {
  970: 		foreach (@$partlist) {
  971: 		    $gradeTable.='<td>&nbsp;</td>';
  972: 		}
  973: 	    } elsif ($submitonly eq 'queued') {
  974: 		$gradeTable.='<td>&nbsp;</td>';
  975: 	    }
  976: 	$gradeTable.='</tr>';
  977:     }
  978: 
  979:     $gradeTable.='</table></td></tr></table>'."\n".
  980: 	'<input type="button" '.
  981: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
  982: 	'value="Next->" /></form>'."\n";
  983:     if ($ctr == 0) {
  984: 	my $num_students=(scalar(keys(%$fullname)));
  985: 	if ($num_students eq 0) {
  986: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
  987: 	} else {
  988: 	    my $submissions='submissions';
  989: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
  990: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
  991: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
  992: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
  993: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
  994: 		' students checked for '.$submissions.')</span><br />';
  995: 	}
  996:     } elsif ($ctr == 1) {
  997: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
  998:     }
  999:     $gradeTable.=&show_grading_menu_form($symb);
 1000:     $request->print($gradeTable);
 1001:     return '';
 1002: }
 1003: 
 1004: #---- Called from the listStudents routine
 1005: 
 1006: sub check_script {
 1007:     my ($form, $type)=@_;
 1008:     my $chkallscript='<script type="text/javascript">
 1009:     function checkall() {
 1010:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1011:             ele = document.forms.'.$form.'.elements[i];
 1012:             if (ele.name == "'.$type.'") {
 1013:             document.forms.'.$form.'.elements[i].checked=true;
 1014:                                        }
 1015:         }
 1016:     }
 1017: 
 1018:     function checksec() {
 1019:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1020:             ele = document.forms.'.$form.'.elements[i];
 1021:            string = document.forms.'.$form.'.chksec.value;
 1022:            if
 1023:           (ele.value.indexOf(":::SECTION"+string)>0) {
 1024:               document.forms.'.$form.'.elements[i].checked=true;
 1025:             }
 1026:         }
 1027:     }
 1028: 
 1029: 
 1030:     function uncheckall() {
 1031:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
 1032:             ele = document.forms.'.$form.'.elements[i];
 1033:             if (ele.name == "'.$type.'") {
 1034:             document.forms.'.$form.'.elements[i].checked=false;
 1035:                                        }
 1036:         }
 1037:     }
 1038: 
 1039: </script>'."\n";
 1040:     return $chkallscript;
 1041: }
 1042: 
 1043: sub check_buttons {
 1044:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
 1045:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
 1046:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
 1047:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
 1048:     return $buttons;
 1049: }
 1050: 
 1051: #     Displays the submissions for one student or a group of students
 1052: sub processGroup {
 1053:     my ($request)  = shift;
 1054:     my $ctr        = 0;
 1055:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1056:     my $total      = scalar(@stuchecked)-1;
 1057: 
 1058:     foreach my $student (@stuchecked) {
 1059: 	my ($uname,$udom,$fullname) = split(/:/,$student);
 1060: 	$env{'form.student'}        = $uname;
 1061: 	$env{'form.userdom'}        = $udom;
 1062: 	$env{'form.fullname'}       = $fullname;
 1063: 	&submission($request,$ctr,$total);
 1064: 	$ctr++;
 1065:     }
 1066:     return '';
 1067: }
 1068: 
 1069: #------------------------------------------------------------------------------------
 1070: #
 1071: #-------------------------- Next few routines handles grading by student, essentially
 1072: #                           handles essay response type problem/part
 1073: #
 1074: #--- Javascript to handle the submission page functionality ---
 1075: sub sub_page_js {
 1076:     my $request = shift;
 1077:     $request->print(<<SUBJAVASCRIPT);
 1078: <script type="text/javascript" language="javascript">
 1079:     function updateRadio(formname,id,weight) {
 1080: 	var gradeBox = formname["GD_BOX"+id];
 1081: 	var radioButton = formname["RADVAL"+id];
 1082: 	var oldpts = formname["oldpts"+id].value;
 1083: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
 1084: 	gradeBox.value = pts;
 1085: 	var resetbox = false;
 1086: 	if (isNaN(pts) || pts < 0) {
 1087: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
 1088: 	    for (var i=0; i<radioButton.length; i++) {
 1089: 		if (radioButton[i].checked) {
 1090: 		    gradeBox.value = i;
 1091: 		    resetbox = true;
 1092: 		}
 1093: 	    }
 1094: 	    if (!resetbox) {
 1095: 		formtextbox.value = "";
 1096: 	    }
 1097: 	    return;
 1098: 	}
 1099: 
 1100: 	if (pts > weight) {
 1101: 	    var resp = confirm("You entered a value ("+pts+
 1102: 			       ") greater than the weight for the part. Accept?");
 1103: 	    if (resp == false) {
 1104: 		gradeBox.value = oldpts;
 1105: 		return;
 1106: 	    }
 1107: 	}
 1108: 
 1109: 	for (var i=0; i<radioButton.length; i++) {
 1110: 	    radioButton[i].checked=false;
 1111: 	    if (pts == i && pts != "") {
 1112: 		radioButton[i].checked=true;
 1113: 	    }
 1114: 	}
 1115: 	updateSelect(formname,id);
 1116: 	formname["stores"+id].value = "0";
 1117:     }
 1118: 
 1119:     function writeBox(formname,id,pts) {
 1120: 	var gradeBox = formname["GD_BOX"+id];
 1121: 	if (checkSolved(formname,id) == 'update') {
 1122: 	    gradeBox.value = pts;
 1123: 	} else {
 1124: 	    var oldpts = formname["oldpts"+id].value;
 1125: 	    gradeBox.value = oldpts;
 1126: 	    var radioButton = formname["RADVAL"+id];
 1127: 	    for (var i=0; i<radioButton.length; i++) {
 1128: 		radioButton[i].checked=false;
 1129: 		if (i == oldpts) {
 1130: 		    radioButton[i].checked=true;
 1131: 		}
 1132: 	    }
 1133: 	}
 1134: 	formname["stores"+id].value = "0";
 1135: 	updateSelect(formname,id);
 1136: 	return;
 1137:     }
 1138: 
 1139:     function clearRadBox(formname,id) {
 1140: 	if (checkSolved(formname,id) == 'noupdate') {
 1141: 	    updateSelect(formname,id);
 1142: 	    return;
 1143: 	}
 1144: 	gradeSelect = formname["GD_SEL"+id];
 1145: 	for (var i=0; i<gradeSelect.length; i++) {
 1146: 	    if (gradeSelect[i].selected) {
 1147: 		var selectx=i;
 1148: 	    }
 1149: 	}
 1150: 	var stores = formname["stores"+id];
 1151: 	if (selectx == stores.value) { return };
 1152: 	var gradeBox = formname["GD_BOX"+id];
 1153: 	gradeBox.value = "";
 1154: 	var radioButton = formname["RADVAL"+id];
 1155: 	for (var i=0; i<radioButton.length; i++) {
 1156: 	    radioButton[i].checked=false;
 1157: 	}
 1158: 	stores.value = selectx;
 1159:     }
 1160: 
 1161:     function checkSolved(formname,id) {
 1162: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
 1163: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
 1164: 	    if (!reply) {return "noupdate";}
 1165: 	    formname.overRideScore.value = 'yes';
 1166: 	}
 1167: 	return "update";
 1168:     }
 1169: 
 1170:     function updateSelect(formname,id) {
 1171: 	formname["GD_SEL"+id][0].selected = true;
 1172: 	return;
 1173:     }
 1174: 
 1175: //=========== Check that a point is assigned for all the parts  ============
 1176:     function checksubmit(formname,val,total,parttot) {
 1177: 	formname.gradeOpt.value = val;
 1178: 	if (val == "Save & Next") {
 1179: 	    for (i=0;i<=total;i++) {
 1180: 		for (j=0;j<parttot;j++) {
 1181: 		    var partid = formname["partid"+i+"_"+j].value;
 1182: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1183: 			var points = formname["GD_BOX"+i+"_"+partid].value;
 1184: 			if (points == "") {
 1185: 			    var name = formname["name"+i].value;
 1186: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
 1187: 			    var resp = confirm("You did not assign a score for "+studentID+
 1188: 					       ", part "+partid+". Continue?");
 1189: 			    if (resp == false) {
 1190: 				formname["GD_BOX"+i+"_"+partid].focus();
 1191: 				return false;
 1192: 			    }
 1193: 			}
 1194: 		    }
 1195: 		    
 1196: 		}
 1197: 	    }
 1198: 	    
 1199: 	}
 1200: 	if (val == "Grade Student") {
 1201: 	    formname.showgrading.value = "yes";
 1202: 	    if (formname.Status.value == "") {
 1203: 		formname.Status.value = "Active";
 1204: 	    }
 1205: 	    formname.studentNo.value = total;
 1206: 	}
 1207: 	formname.submit();
 1208:     }
 1209: 
 1210: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
 1211:     function checkSubmitPage(formname,total) {
 1212: 	noscore = new Array(100);
 1213: 	var ptr = 0;
 1214: 	for (i=1;i<total;i++) {
 1215: 	    var partid = formname["q_"+i].value;
 1216: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
 1217: 		var points = formname["GD_BOX"+i+"_"+partid].value;
 1218: 		var status = formname["solved"+i+"_"+partid].value;
 1219: 		if (points == "" && status != "correct_by_student") {
 1220: 		    noscore[ptr] = i;
 1221: 		    ptr++;
 1222: 		}
 1223: 	    }
 1224: 	}
 1225: 	if (ptr != 0) {
 1226: 	    var sense = ptr == 1 ? ": " : "s: ";
 1227: 	    var prolist = "";
 1228: 	    if (ptr == 1) {
 1229: 		prolist = noscore[0];
 1230: 	    } else {
 1231: 		var i = 0;
 1232: 		while (i < ptr-1) {
 1233: 		    prolist += noscore[i]+", ";
 1234: 		    i++;
 1235: 		}
 1236: 		prolist += "and "+noscore[i];
 1237: 	    }
 1238: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
 1239: 	    if (resp == false) {
 1240: 		return false;
 1241: 	    }
 1242: 	}
 1243: 
 1244: 	formname.submit();
 1245:     }
 1246: </script>
 1247: SUBJAVASCRIPT
 1248: }
 1249: 
 1250: #--- javascript for essay type problem --
 1251: sub sub_page_kw_js {
 1252:     my $request = shift;
 1253:     my $iconpath = $request->dir_config('lonIconsURL');
 1254:     &commonJSfunctions($request);
 1255: 
 1256:     my $inner_js_msg_central=<<INNERJS;
 1257:     <script text="text/javascript">
 1258:     function checkInput() {
 1259:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
 1260:       var nmsg   = opener.document.SCORE.savemsgN.value;
 1261:       var usrctr = document.msgcenter.usrctr.value;
 1262:       var newval = opener.document.SCORE["newmsg"+usrctr];
 1263:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
 1264: 
 1265:       var msgchk = "";
 1266:       if (document.msgcenter.subchk.checked) {
 1267:          msgchk = "msgsub,";
 1268:       }
 1269:       var includemsg = 0;
 1270:       for (var i=1; i<=nmsg; i++) {
 1271:           var opnmsg = opener.document.SCORE["savemsg"+i];
 1272:           var frmmsg = document.msgcenter["msg"+i];
 1273:           opnmsg.value = opener.checkEntities(frmmsg.value);
 1274:           var showflg = opener.document.SCORE["shownOnce"+i];
 1275:           showflg.value = "1";
 1276:           var chkbox = document.msgcenter["msgn"+i];
 1277:           if (chkbox.checked) {
 1278:              msgchk += "savemsg"+i+",";
 1279:              includemsg = 1;
 1280:           }
 1281:       }
 1282:       if (document.msgcenter.newmsgchk.checked) {
 1283:          msgchk += "newmsg"+usrctr;
 1284:          includemsg = 1;
 1285:       }
 1286:       imgformname = opener.document.SCORE["mailicon"+usrctr];
 1287:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
 1288:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
 1289:       includemsg.value = msgchk;
 1290: 
 1291:       self.close()
 1292: 
 1293:     }
 1294:     </script>
 1295: INNERJS
 1296: 
 1297:     my $inner_js_highlight_central=<<INNERJS;
 1298:  <script type="text/javascript">
 1299:     function updateChoice(flag) {
 1300:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
 1301:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
 1302:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
 1303:       opener.document.SCORE.refresh.value = "on";
 1304:       if (opener.document.SCORE.keywords.value!=""){
 1305:          opener.document.SCORE.submit();
 1306:       }
 1307:       self.close()
 1308:     }
 1309: </script>
 1310: INNERJS
 1311: 
 1312:     my $start_page_msg_central = 
 1313:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
 1314: 				       {'js_ready'  => 1,
 1315: 					'only_body' => 1,
 1316: 					'bgcolor'   =>'#FFFFFF',});
 1317:     my $end_page_msg_central = 
 1318: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1319: 
 1320: 
 1321:     my $start_page_highlight_central = 
 1322:         &Apache::loncommon::start_page('Highlight Central',
 1323: 				       $inner_js_highlight_central,
 1324: 				       {'js_ready'  => 1,
 1325: 					'only_body' => 1,
 1326: 					'bgcolor'   =>'#FFFFFF',});
 1327:     my $end_page_highlight_central = 
 1328: 	&Apache::loncommon::end_page({'js_ready' => 1});
 1329: 
 1330:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
 1331:     $docopen=~s/^document\.//;
 1332:     $request->print(<<SUBJAVASCRIPT);
 1333: <script type="text/javascript" language="javascript">
 1334: 
 1335: //===================== Show list of keywords ====================
 1336:   function keywords(formname) {
 1337:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
 1338:     if (nret==null) return;
 1339:     formname.keywords.value = nret;
 1340: 
 1341:     if (formname.keywords.value != "") {
 1342: 	formname.refresh.value = "on";
 1343: 	formname.submit();
 1344:     }
 1345:     return;
 1346:   }
 1347: 
 1348: //===================== Script to view submitted by ==================
 1349:   function viewSubmitter(submitter) {
 1350:     document.SCORE.refresh.value = "on";
 1351:     document.SCORE.NCT.value = "1";
 1352:     document.SCORE.unamedom0.value = submitter;
 1353:     document.SCORE.submit();
 1354:     return;
 1355:   }
 1356: 
 1357: //===================== Script to add keyword(s) ==================
 1358:   function getSel() {
 1359:     if (document.getSelection) txt = document.getSelection();
 1360:     else if (document.selection) txt = document.selection.createRange().text;
 1361:     else return;
 1362:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
 1363:     if (cleantxt=="") {
 1364: 	alert("Please select a word or group of words from document and then click this link.");
 1365: 	return;
 1366:     }
 1367:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
 1368:     if (nret==null) return;
 1369:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
 1370:     if (document.SCORE.keywords.value != "") {
 1371: 	document.SCORE.refresh.value = "on";
 1372: 	document.SCORE.submit();
 1373:     }
 1374:     return;
 1375:   }
 1376: 
 1377: //====================== Script for composing message ==============
 1378:    // preload images
 1379:    img1 = new Image();
 1380:    img1.src = "$iconpath/mailbkgrd.gif";
 1381:    img2 = new Image();
 1382:    img2.src = "$iconpath/mailto.gif";
 1383: 
 1384:   function msgCenter(msgform,usrctr,fullname) {
 1385:     var Nmsg  = msgform.savemsgN.value;
 1386:     savedMsgHeader(Nmsg,usrctr,fullname);
 1387:     var subject = msgform.msgsub.value;
 1388:     var msgchk = document.SCORE["includemsg"+usrctr].value;
 1389:     re = /msgsub/;
 1390:     var shwsel = "";
 1391:     if (re.test(msgchk)) { shwsel = "checked" }
 1392:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
 1393:     displaySubject(checkEntities(subject),shwsel);
 1394:     for (var i=1; i<=Nmsg; i++) {
 1395: 	var testmsg = "savemsg"+i+",";
 1396: 	re = new RegExp(testmsg,"g");
 1397: 	shwsel = "";
 1398: 	if (re.test(msgchk)) { shwsel = "checked" }
 1399: 	var message = document.SCORE["savemsg"+i].value;
 1400: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
 1401: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
 1402: 	                                   //any &lt; is already converted to <, etc. However, only once!!
 1403:     }
 1404:     newmsg = document.SCORE["newmsg"+usrctr].value;
 1405:     shwsel = "";
 1406:     re = /newmsg/;
 1407:     if (re.test(msgchk)) { shwsel = "checked" }
 1408:     newMsg(newmsg,shwsel);
 1409:     msgTail(); 
 1410:     return;
 1411:   }
 1412: 
 1413:   function checkEntities(strx) {
 1414:     if (strx.length == 0) return strx;
 1415:     var orgStr = ["&", "<", ">", '"']; 
 1416:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
 1417:     var counter = 0;
 1418:     while (counter < 4) {
 1419: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
 1420: 	counter++;
 1421:     }
 1422:     return strx;
 1423:   }
 1424: 
 1425:   function strReplace(strx, orgStr, newStr) {
 1426:     return strx.split(orgStr).join(newStr);
 1427:   }
 1428: 
 1429:   function savedMsgHeader(Nmsg,usrctr,fullname) {
 1430:     var height = 70*Nmsg+250;
 1431:     var scrollbar = "no";
 1432:     if (height > 600) {
 1433: 	height = 600;
 1434: 	scrollbar = "yes";
 1435:     }
 1436:     var xpos = (screen.width-600)/2;
 1437:     xpos = (xpos < 0) ? '0' : xpos;
 1438:     var ypos = (screen.height-height)/2-30;
 1439:     ypos = (ypos < 0) ? '0' : ypos;
 1440: 
 1441:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
 1442:     pWin.focus();
 1443:     pDoc = pWin.document;
 1444:     pDoc.$docopen;
 1445:     pDoc.write('$start_page_msg_central');
 1446: 
 1447:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
 1448:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
 1449:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
 1450: 
 1451:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1452:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1453:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
 1454: }
 1455:     function displaySubject(msg,shwsel) {
 1456:     pDoc = pWin.document;
 1457:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1458:     pDoc.write("<td>Subject</td>");
 1459:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
 1460:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
 1461: }
 1462: 
 1463:   function displaySavedMsg(ctr,msg,shwsel) {
 1464:     pDoc = pWin.document;
 1465:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1466:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
 1467:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
 1468:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
 1469: }
 1470: 
 1471:   function newMsg(newmsg,shwsel) {
 1472:     pDoc = pWin.document;
 1473:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1474:     pDoc.write("<td align=\\"center\\">New</td>");
 1475:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
 1476:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
 1477: }
 1478: 
 1479:   function msgTail() {
 1480:     pDoc = pWin.document;
 1481:     pDoc.write("</table>");
 1482:     pDoc.write("</td></tr></table>&nbsp;");
 1483:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
 1484:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1485:     pDoc.write("</form>");
 1486:     pDoc.write('$end_page_msg_central');
 1487:     pDoc.close();
 1488: }
 1489: 
 1490: //====================== Script for keyword highlight options ==============
 1491:   function kwhighlight() {
 1492:     var kwclr    = document.SCORE.kwclr.value;
 1493:     var kwsize   = document.SCORE.kwsize.value;
 1494:     var kwstyle  = document.SCORE.kwstyle.value;
 1495:     var redsel = "";
 1496:     var grnsel = "";
 1497:     var blusel = "";
 1498:     if (kwclr=="red")   {var redsel="checked"};
 1499:     if (kwclr=="green") {var grnsel="checked"};
 1500:     if (kwclr=="blue")  {var blusel="checked"};
 1501:     var sznsel = "";
 1502:     var sz1sel = "";
 1503:     var sz2sel = "";
 1504:     if (kwsize=="0")  {var sznsel="checked"};
 1505:     if (kwsize=="+1") {var sz1sel="checked"};
 1506:     if (kwsize=="+2") {var sz2sel="checked"};
 1507:     var synsel = "";
 1508:     var syisel = "";
 1509:     var sybsel = "";
 1510:     if (kwstyle=="")    {var synsel="checked"};
 1511:     if (kwstyle=="<i>") {var syisel="checked"};
 1512:     if (kwstyle=="<b>") {var sybsel="checked"};
 1513:     highlightCentral();
 1514:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
 1515:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
 1516:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
 1517:     highlightend();
 1518:     return;
 1519:   }
 1520: 
 1521:   function highlightCentral() {
 1522: //    if (window.hwdWin) window.hwdWin.close();
 1523:     var xpos = (screen.width-400)/2;
 1524:     xpos = (xpos < 0) ? '0' : xpos;
 1525:     var ypos = (screen.height-330)/2-30;
 1526:     ypos = (ypos < 0) ? '0' : ypos;
 1527: 
 1528:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
 1529:     hwdWin.focus();
 1530:     var hDoc = hwdWin.document;
 1531:     hDoc.$docopen;
 1532:     hDoc.write('$start_page_highlight_central');
 1533:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
 1534:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
 1535: 
 1536:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
 1537:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
 1538:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
 1539:   }
 1540: 
 1541:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
 1542:     var hDoc = hwdWin.document;
 1543:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
 1544:     hDoc.write("<td align=\\"left\\">");
 1545:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
 1546:     hDoc.write("<td align=\\"left\\">");
 1547:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
 1548:     hDoc.write("<td align=\\"left\\">");
 1549:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
 1550:     hDoc.write("</tr>");
 1551:   }
 1552: 
 1553:   function highlightend() { 
 1554:     var hDoc = hwdWin.document;
 1555:     hDoc.write("</table>");
 1556:     hDoc.write("</td></tr></table>&nbsp;");
 1557:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
 1558:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
 1559:     hDoc.write("</form>");
 1560:     hDoc.write('$end_page_highlight_central');
 1561:     hDoc.close();
 1562:   }
 1563: 
 1564: </script>
 1565: SUBJAVASCRIPT
 1566: }
 1567: 
 1568: sub get_increment {
 1569:     my $increment = $env{'form.increment'};
 1570:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
 1571:         $increment != .1) {
 1572:         $increment = 1;
 1573:     }
 1574:     return $increment;
 1575: }
 1576: 
 1577: #--- displays the grading box, used in essay type problem and grading by page/sequence
 1578: sub gradeBox {
 1579:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
 1580:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1581: 	'" src="'.$request->dir_config('lonIconsURL').
 1582: 	'/check.gif" height="16" border="0" />';
 1583:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
 1584:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
 1585: 		  '<span class="LC_info">problem weight assigned by computer</span>');
 1586:     $wgt       = ($wgt > 0 ? $wgt : '1');
 1587:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
 1588: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
 1589:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
 1590:     my $display_part=&get_display_part($partid,$symb);
 1591:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 1592: 				       [$partid]);
 1593:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
 1594:     if ($last_resets{$partid}) {
 1595:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
 1596:     }
 1597:     $result.='<table border="0"><tr><td>'.
 1598: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
 1599:     my $ctr = 0;
 1600:     my $thisweight = 0;
 1601:     my $increment = &get_increment();
 1602:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
 1603:     while ($thisweight<=$wgt) {
 1604: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
 1605: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
 1606: 	    $thisweight.')" value="'.$thisweight.'" '.
 1607: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
 1608: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 1609:         $thisweight += $increment;
 1610: 	$ctr++;
 1611:     }
 1612:     $result.='</tr></table>';
 1613:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
 1614:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
 1615: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
 1616: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
 1617: 	$wgt.')" /></td>'."\n";
 1618:     $result.='<td>/'.$wgt.' '.$wgtmsg.
 1619: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
 1620: 	' </td><td>'."\n";
 1621:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
 1622: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
 1623:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
 1624: 	$result.='<option></option>'.
 1625: 	    '<option selected="selected">excused</option>';
 1626:     } else {
 1627: 	$result.='<option selected="selected"></option>'.
 1628: 	    '<option>excused</option>';
 1629:     }
 1630:     $result.='<option>reset status</option></select>'."\n";
 1631:     $result.="&nbsp;&nbsp;\n";
 1632:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
 1633: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
 1634: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
 1635: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
 1636:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
 1637:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
 1638:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
 1639:         $aggtries.'" />'."\n";
 1640:     $result.='</td></tr></table>'."\n";
 1641:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
 1642:     return $result;
 1643: }
 1644: 
 1645: sub handback_box {
 1646:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
 1647:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1648:     my (@respids);
 1649:      my @part_response_id = &flatten_responseType($responseType);
 1650:     foreach my $part_response_id (@part_response_id) {
 1651:     	my ($part,$resp) = @{ $part_response_id };
 1652:         if ($part eq $partid) {
 1653:             push(@respids,$resp);
 1654:         }
 1655:     }
 1656:     my $result;
 1657:     foreach my $respid (@respids) {
 1658: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
 1659: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
 1660: 	next if (!@$files);
 1661: 	my $file_counter = 1;
 1662: 	foreach my $file (@$files) {
 1663: 	    if ($file =~ /\/portfolio\//) {
 1664:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
 1665:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
 1666:     	        $file_disp = "$name.$ext";
 1667:     	        $file = $file_path.$file_disp;
 1668:     	        $result.=&mt('Return commented version of [_1] to student.',
 1669:     			 '<span class="LC_filename">'.$file_disp.'</span>');
 1670:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
 1671:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
 1672:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
 1673:     	        $file_counter++;
 1674: 	    }
 1675: 	}
 1676:     }
 1677:     return $result;    
 1678: }
 1679: 
 1680: sub show_problem {
 1681:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
 1682:     my $rendered;
 1683:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
 1684:     &Apache::lonxml::remember_problem_counter();
 1685:     if ($mode eq 'both' or $mode eq 'text') {
 1686: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
 1687: 						       $env{'request.course.id'},
 1688: 						       undef,\%form);
 1689:     }
 1690:     if ($removeform) {
 1691: 	$rendered=~s|<form(.*?)>||g;
 1692: 	$rendered=~s|</form>||g;
 1693: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
 1694:     }
 1695:     my $companswer;
 1696:     if ($mode eq 'both' or $mode eq 'answer') {
 1697: 	&Apache::lonxml::restore_problem_counter();
 1698: 	$companswer=
 1699: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
 1700: 						    $env{'request.course.id'},
 1701: 						    %form);
 1702:     }
 1703:     if ($removeform) {
 1704: 	$companswer=~s|<form(.*?)>||g;
 1705: 	$companswer=~s|</form>||g;
 1706: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
 1707:     }
 1708:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
 1709:     $result.='<table border="0" width="100%">';
 1710:     if ($viewon) {
 1711: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
 1712: 	if ($mode eq 'both' or $mode eq 'text') {
 1713: 	    $result.='View of the problem - ';
 1714: 	} else {
 1715: 	    $result.='Correct answer: ';
 1716: 	}
 1717: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
 1718:     }
 1719:     if ($mode eq 'both') {
 1720: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
 1721: 	$result.='<b>Correct answer:</b><br />'.$companswer;
 1722:     } elsif ($mode eq 'text') {
 1723: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
 1724:     } elsif ($mode eq 'answer') {
 1725: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
 1726:     }
 1727:     $result.='</td></tr></table>';
 1728:     $result.='</td></tr></table><br />';
 1729:     return $result;
 1730: }
 1731: 
 1732: sub files_exist {
 1733:     my ($r, $symb) = @_;
 1734:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
 1735: 
 1736:     foreach my $student (@students) {
 1737:         my ($uname,$udom,$fullname) = split(/:/,$student);
 1738:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
 1739: 					      $udom,$uname);
 1740:         my ($string,$timestamp)= &get_last_submission(\%record);
 1741:         foreach my $submission (@$string) {
 1742:             my ($partid,$respid) =
 1743: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
 1744:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
 1745: 					   \%record);
 1746:             return 1 if (@$files);
 1747:         }
 1748:     }
 1749:     return 0;
 1750: }
 1751: 
 1752: sub download_all_link {
 1753:     my ($r,$symb) = @_;
 1754:     my $all_students = 
 1755: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
 1756: 
 1757:     my $parts =
 1758: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
 1759: 
 1760:     my $identifier = &Apache::loncommon::get_cgi_id();
 1761:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
 1762:                             'cgi.'.$identifier.'.symb' => $symb,
 1763:                             'cgi.'.$identifier.'.parts' => $parts,);
 1764:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
 1765: 	      &mt('Download All Submitted Documents').'</a>');
 1766:     return
 1767: }
 1768: 
 1769: sub build_section_inputs {
 1770:     my $section_inputs;
 1771:     if ($env{'form.section'} eq '') {
 1772:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
 1773:     } else {
 1774:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
 1775:         foreach my $section (@sections) {
 1776:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
 1777:         }
 1778:     }
 1779:     return $section_inputs;
 1780: }
 1781: 
 1782: # --------------------------- show submissions of a student, option to grade 
 1783: sub submission {
 1784:     my ($request,$counter,$total) = @_;
 1785: 
 1786:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
 1787:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
 1788:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
 1789:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
 1790:     my $symb = &get_symb($request); 
 1791:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
 1792: 
 1793:     if (!&canview($usec)) {
 1794: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
 1795: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
 1796: 			$env{'request.course.id'}.')</span>');
 1797: 	$request->print(&show_grading_menu_form($symb));
 1798: 	return;
 1799:     }
 1800: 
 1801:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
 1802:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
 1803:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
 1804:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 1805:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 1806: 	'" src="'.$request->dir_config('lonIconsURL').
 1807: 	'/check.gif" height="16" border="0" />';
 1808: 
 1809:     my %old_essays;
 1810:     # header info
 1811:     if ($counter == 0) {
 1812: 	&sub_page_js($request);
 1813: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
 1814: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
 1815: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
 1816: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
 1817: 	    &download_all_link($request, $symb);
 1818: 	}
 1819: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
 1820: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
 1821: 
 1822: 	if ($env{'form.handgrade'} eq 'no') {
 1823: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
 1824: 		$checkIcon.' symbol.'."\n";
 1825: 	    $request->print($checkMark);
 1826: 	}
 1827: 
 1828: 	# option to display problem, only once else it cause problems 
 1829:         # with the form later since the problem has a form.
 1830: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
 1831: 	    my $mode;
 1832: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
 1833: 		$mode='both';
 1834: 	    } elsif ($env{'form.vProb'} eq 'yes') {
 1835: 		$mode='text';
 1836: 	    } elsif ($env{'form.vAns'} eq 'yes') {
 1837: 		$mode='answer';
 1838: 	    }
 1839: 	    &Apache::lonxml::clear_problem_counter();
 1840: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
 1841: 	}
 1842: 
 1843: 	# kwclr is the only variable that is guaranteed to be non blank 
 1844:         # if this subroutine has been called once.
 1845: 	my %keyhash = ();
 1846: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
 1847: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
 1848: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
 1849: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
 1850: 
 1851: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 1852: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
 1853: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
 1854: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
 1855: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
 1856: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
 1857: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
 1858: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
 1859: 	}
 1860: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
 1861: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 1862: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
 1863: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
 1864: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 1865: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
 1866: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
 1867: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
 1868: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 1869: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
 1870: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
 1871: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 1872: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
 1873: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
 1874: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
 1875: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
 1876: 			&build_section_inputs().
 1877: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
 1878: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
 1879: 			'<input type="hidden" name="NCT"'.
 1880: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
 1881: 	if ($env{'form.handgrade'} eq 'yes') {
 1882: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
 1883: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
 1884: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
 1885: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
 1886: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
 1887: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
 1888: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
 1889: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
 1890: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
 1891: 	    }
 1892: 	}
 1893: 	
 1894: 	my ($cts,$prnmsg) = (1,'');
 1895: 	while ($cts <= $env{'form.savemsgN'}) {
 1896: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
 1897: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
 1898: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
 1899: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 1900: 		'" />'."\n".
 1901: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
 1902: 	    $cts++;
 1903: 	}
 1904: 	$request->print($prnmsg);
 1905: 
 1906: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
 1907: #
 1908: # Print out the keyword options line
 1909: #
 1910: 	    $request->print(<<KEYWORDS);
 1911: &nbsp;<b>Keyword Options:</b>&nbsp;
 1912: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
 1913: <a href="#" onMouseDown="javascript:getSel(); return false"
 1914:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 1915: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
 1916: KEYWORDS
 1917: #
 1918: # Load the other essays for similarity check
 1919: #
 1920:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
 1921: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
 1922: 	    $apath=&escape($apath);
 1923: 	    $apath=~s/\W/\_/gs;
 1924: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
 1925:         }
 1926:     }
 1927: 
 1928: # This is where output for one specific student would start
 1929:     my $bgcolor='#DDEEDD';
 1930:     if (int($counter/2) eq $counter) { $bgcolor='#DDDDEE'; }
 1931:     $request->print("\n\n".
 1932:                     '<p><table border="2"><tr><th bgcolor="'.$bgcolor.'">'.$env{'form.fullname'}.'</th></tr><tr><td bgcolor="'.$bgcolor.'">');
 1933: 
 1934:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
 1935: 	my $mode;
 1936: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
 1937: 	    $mode='both';
 1938: 	} elsif ($env{'form.vProb'} eq 'all' ) {
 1939: 	    $mode='text';
 1940: 	} elsif ($env{'form.vAns'} eq 'all') {
 1941: 	    $mode='answer';
 1942: 	}
 1943: 	&Apache::lonxml::clear_problem_counter();
 1944: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
 1945:     }
 1946: 
 1947:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 1948:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 1949: 
 1950:     # Display student info
 1951:     $request->print(($counter == 0 ? '' : '<br />'));
 1952:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
 1953: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
 1954: 
 1955:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
 1956:     $result.='<input type="hidden" name="name'.$counter.
 1957: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
 1958: 
 1959:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
 1960:     my @col_fullnames;
 1961:     my ($classlist,$fullname);
 1962:     if ($env{'form.handgrade'} eq 'yes') {
 1963: 	($classlist,undef,$fullname) = &getclasslist('all','0');
 1964: 	for (keys (%$handgrade)) {
 1965: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
 1966: 					    '.maxcollaborators',
 1967:                                             $symb,$udom,$uname);
 1968: 	    next if ($ncol <= 0);
 1969:             s/\_/\./g;
 1970:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
 1971:             my @goodcollaborators = ();
 1972:             my @badcollaborators  = ();
 1973: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
 1974: 		$_ =~ s/[\$\^\(\)]//g;
 1975: 		next if ($_ eq '');
 1976: 		my ($co_name,$co_dom) = split /\@|:/,$_;
 1977: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
 1978: 		next if ($co_name eq $uname && $co_dom eq $udom);
 1979: 		# Doing this grep allows 'fuzzy' specification
 1980: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
 1981: 		if (! scalar(@Matches)) {
 1982: 		    push @badcollaborators,$_;
 1983: 		} else {
 1984: 		    push @goodcollaborators, @Matches;
 1985: 		}
 1986: 	    }
 1987:             if (scalar(@goodcollaborators) != 0) {
 1988:                 $result.='<b>Collaborators: </b>';
 1989:                 foreach (@goodcollaborators) {
 1990: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
 1991: 		    push @col_fullnames, $givenn.' '.$lastname;
 1992: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
 1993: 		}
 1994:                 $result.='<br />'."\n";
 1995: 		my ($part)=split(/\./,$_);
 1996: 		$result.='<input type="hidden" name="collaborator'.$counter.
 1997: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
 1998: 		    "\n";
 1999: 	    }
 2000: 	    if (scalar(@badcollaborators) > 0) {
 2001: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
 2002: 		$result.='This student has submitted ';
 2003: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
 2004: 		$result .= ': '.join(', ',@badcollaborators);
 2005: 		$result .= '</td></tr></table>';
 2006: 	    }         
 2007: 	    if (scalar(@badcollaborators > $ncol)) {
 2008: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
 2009: 		$result .= 'This student has submitted too many '.
 2010: 		    'collaborators.  Maximum is '.$ncol.'.';
 2011: 		$result .= '</td></tr></table>';
 2012: 	    }
 2013: 	}
 2014:     }
 2015:     $request->print($result."\n");
 2016: 
 2017:     # print student answer/submission
 2018:     # Options are (1) Handgaded submission only
 2019:     #             (2) Last submission, includes submission that is not handgraded 
 2020:     #                  (for multi-response type part)
 2021:     #             (3) Last submission plus the parts info
 2022:     #             (4) The whole record for this student
 2023:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
 2024: 	my ($string,$timestamp)= &get_last_submission(\%record);
 2025: 	my $lastsubonly=''.
 2026: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
 2027: 	     $$timestamp)."</td></tr>\n";
 2028: 	if ($$timestamp eq '') {
 2029: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
 2030: 	} else {
 2031: 	    my %seenparts;
 2032: 	    my @part_response_id = &flatten_responseType($responseType);
 2033: 	    foreach my $part (@part_response_id) {
 2034: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
 2035: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
 2036: 
 2037: 		my ($partid,$respid) = @{ $part };
 2038: 		my $display_part=&get_display_part($partid,$symb);
 2039: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
 2040: 		    if (exists($seenparts{$partid})) { next; }
 2041: 		    $seenparts{$partid}=1;
 2042: 		    my $submitby='<b>Part:</b> '.$display_part.
 2043: 			' <b>Collaborative submission by:</b> '.
 2044: 			'<a href="javascript:viewSubmitter(\''.
 2045: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
 2046: 			'\');" target="_self">'.
 2047: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
 2048: 		    $request->print($submitby);
 2049: 		    next;
 2050: 		}
 2051: 		my $responsetype = $responseType->{$partid}->{$respid};
 2052: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
 2053: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
 2054: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
 2055: 			' )</span>&nbsp; &nbsp;'.
 2056: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
 2057: 		    next;
 2058: 		}
 2059: 		foreach (@$string) {
 2060: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
 2061: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
 2062: 		    my ($ressub,$subval) = split(/:/,$_,2);
 2063: 		    # Similarity check
 2064: 		    my $similar='';
 2065: 		    if($env{'form.checkPlag'}){
 2066: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
 2067: 			    &most_similar($uname,$udom,$subval,\%old_essays);
 2068: 			if ($osim) {
 2069: 			    $osim=int($osim*100.0);
 2070: 			    my %old_course_desc = 
 2071: 				&Apache::lonnet::coursedescription($ocrsid,
 2072: 								   {'one_time' => 1});
 2073: 
 2074: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
 2075: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
 2076: 				    $osim,
 2077: 				    &Apache::loncommon::plainname($oname,$odom),
 2078: 				    $oname,$odom,
 2079: 				    $old_course_desc{'description'},
 2080: 				    $old_course_desc{'num'},
 2081: 				    $old_course_desc{'domain'}).
 2082: 				'</span></h3><blockquote><i>'.
 2083: 				&keywords_highlight($oessay).
 2084: 				'</i></blockquote><hr />';
 2085: 			}
 2086: 		    }
 2087: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
 2088: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
 2089: 			($env{'form.lastSub'} eq 'hdgrade' && 
 2090: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
 2091: 			my $display_part=&get_display_part($partid,$symb);
 2092: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
 2093: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
 2094: 			    ' )</span>&nbsp; &nbsp;';
 2095: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
 2096: 			if (@$files) {
 2097: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
 2098: 			    my $file_counter = 0;
 2099: 			    foreach my $file (@$files) {
 2100: 			        $file_counter ++;
 2101: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
 2102: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
 2103: 			    }
 2104: 			    $lastsubonly.='<br />';
 2105: 			}
 2106: 			$lastsubonly.='<b>Submitted Answer: </b>'.
 2107: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
 2108: 					 $respid,\%record,$order);
 2109: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
 2110: 		    }
 2111: 		}
 2112: 	    }
 2113: 	}
 2114: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
 2115: 	$request->print($lastsubonly);
 2116:     } elsif ($env{'form.lastSub'} eq 'datesub') {
 2117: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
 2118: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
 2119:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
 2120: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
 2121: 								 $env{'request.course.id'},
 2122: 								 $last,'.submission',
 2123: 								 'Apache::grades::keywords_highlight'));
 2124:     }
 2125: 
 2126:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
 2127: 	.$udom.'" />'."\n");
 2128:     
 2129:     # return if view submission with no grading option
 2130:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
 2131: 	my $toGrade.='<input type="button" value="Grade Student" '.
 2132: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
 2133: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
 2134: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
 2135: 	if (($env{'form.command'} eq 'submission') || 
 2136: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
 2137: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
 2138: 	}
 2139: 	$request->print($toGrade);
 2140: 	return;
 2141:     } else {
 2142: 	$request->print('</td></tr></table></td></tr></table>'."\n");
 2143:     }
 2144: 
 2145:     # essay grading message center
 2146:     if ($env{'form.handgrade'} eq 'yes') {
 2147: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
 2148: 	my $msgfor = $givenn.' '.$lastname;
 2149: 	if (scalar(@col_fullnames) > 0) {
 2150: 	    my $lastone = pop @col_fullnames;
 2151: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
 2152: 	}
 2153: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
 2154: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
 2155: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
 2156: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 2157: 	    ',\''.$msgfor.'\');" target="_self">'.
 2158: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
 2159: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
 2160: 	    '<img src="'.$request->dir_config('lonIconsURL').
 2161: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 2162: 	    '<br />&nbsp;('.
 2163: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
 2164: 	$request->print($result);
 2165:     }
 2166:     if ($perm{'vgr'}) {
 2167: 	$request->print('<br />'.
 2168: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
 2169: 						   $uname,$udom,'check'));
 2170:     }
 2171:     if ($perm{'opa'}) {
 2172: 	$request->print('<br />'.
 2173: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
 2174: 					 $uname,$udom,$symb,'check'));
 2175:     }
 2176: 
 2177:     my %seen = ();
 2178:     my @partlist;
 2179:     my @gradePartRespid;
 2180:     my @part_response_id = &flatten_responseType($responseType);
 2181:     foreach my $part_response_id (@part_response_id) {
 2182:     	my ($partid,$respid) = @{ $part_response_id };
 2183: 	my $part_resp = join('_',@{ $part_response_id });
 2184: 	next if ($seen{$partid} > 0);
 2185: 	$seen{$partid}++;
 2186: 	next if ($$handgrade{$part_resp} ne 'yes' 
 2187: 		 && $env{'form.lastSub'} eq 'hdgrade');
 2188: 	push @partlist,$partid;
 2189: 	push @gradePartRespid,$partid.'.'.$respid;
 2190: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
 2191:     }
 2192:     $result='<input type="hidden" name="partlist'.$counter.
 2193: 	'" value="'.(join ":",@partlist).'" />'."\n";
 2194:     $result.='<input type="hidden" name="gradePartRespid'.
 2195: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
 2196:     my $ctr = 0;
 2197:     while ($ctr < scalar(@partlist)) {
 2198: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
 2199: 	    $partlist[$ctr].'" />'."\n";
 2200: 	$ctr++;
 2201:     }
 2202:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
 2203: 
 2204: # Done with printing info for one student
 2205: 
 2206:     $request->print('</td></tr></table></p>');
 2207: 
 2208: 
 2209:     # print end of form
 2210:     if ($counter == $total) {
 2211: 	my $endform='<table border="0"><tr><td>'."\n";
 2212: 	$endform.='<input type="button" value="Save & Next" '.
 2213: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
 2214: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
 2215: 	my $ntstu ='<select name="NTSTU">'.
 2216: 	    '<option>1</option><option>2</option>'.
 2217: 	    '<option>3</option><option>5</option>'.
 2218: 	    '<option>7</option><option>10</option></select>'."\n";
 2219: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
 2220: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
 2221: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
 2222: 	$endform.='<input type="button" value="Previous" '.
 2223: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
 2224: 	    '<input type="button" value="Next" '.
 2225: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
 2226: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
 2227:         $endform.="<input type='hidden' value='".&get_increment().
 2228:             "' name='increment' />";
 2229: 	$endform.='</td><tr></table></form>';
 2230: 	$endform.=&show_grading_menu_form($symb);
 2231: 	$request->print($endform);
 2232:     }
 2233:     return '';
 2234: }
 2235: 
 2236: #--- Retrieve the last submission for all the parts
 2237: sub get_last_submission {
 2238:     my ($returnhash)=@_;
 2239:     my (@string,$timestamp);
 2240:     if ($$returnhash{'version'}) {
 2241: 	my %lasthash=();
 2242: 	my ($version);
 2243: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
 2244: 	    foreach my $key (sort(split(/\:/,
 2245: 					$$returnhash{$version.':keys'}))) {
 2246: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
 2247: 		$timestamp = 
 2248: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
 2249: 	    }
 2250: 	}
 2251: 	foreach my $key (keys(%lasthash)) {
 2252: 	    next if ($key !~ /\.submission$/);
 2253: 
 2254: 	    my ($partid,$foo) = split(/submission$/,$key);
 2255: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
 2256: 		'<span class="LC_warning">Draft Copy</span> ' : '';
 2257: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
 2258: 	}
 2259:     }
 2260:     if (!@string) {
 2261: 	$string[0] =
 2262: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
 2263:     }
 2264:     return (\@string,\$timestamp);
 2265: }
 2266: 
 2267: #--- High light keywords, with style choosen by user.
 2268: sub keywords_highlight {
 2269:     my $string    = shift;
 2270:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
 2271:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
 2272:     (my $styleoff = $styleon) =~ s/\</\<\//;
 2273:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
 2274:     foreach my $keyword (@keylist) {
 2275: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
 2276:     }
 2277:     return $string;
 2278: }
 2279: 
 2280: #--- Called from submission routine
 2281: sub processHandGrade {
 2282:     my ($request) = shift;
 2283:     my $symb   = &get_symb($request);
 2284:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2285:     my $button = $env{'form.gradeOpt'};
 2286:     my $ngrade = $env{'form.NCT'};
 2287:     my $ntstu  = $env{'form.NTSTU'};
 2288:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2289:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
 2290: 
 2291:     if ($button eq 'Save & Next') {
 2292: 	my $ctr = 0;
 2293: 	while ($ctr < $ngrade) {
 2294: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
 2295: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
 2296: 	    if ($errorflag eq 'no_score') {
 2297: 		$ctr++;
 2298: 		next;
 2299: 	    }
 2300: 	    if ($errorflag eq 'not_allowed') {
 2301: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
 2302: 		$ctr++;
 2303: 		next;
 2304: 	    }
 2305: 	    my $includemsg = $env{'form.includemsg'.$ctr};
 2306: 	    my ($subject,$message,$msgstatus) = ('','','');
 2307: 	    my $restitle = &Apache::lonnet::gettitle($symb);
 2308:             my ($feedurl,$showsymb) =
 2309: 		&get_feedurl_and_symb($symb,$uname,$udom);
 2310: 	    my $messagetail;
 2311: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
 2312: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
 2313: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
 2314: 		$subject.=' ['.$restitle.']';
 2315: 		my (@msgnum) = split(/,/,$includemsg);
 2316: 		foreach (@msgnum) {
 2317: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 2318: 		}
 2319: 		$message =&Apache::lonfeedback::clear_out_html($message);
 2320: 		if ($env{'form.withgrades'.$ctr}) {
 2321: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
 2322: 		    $messagetail = " for <a href=\"".
 2323: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2324: 		}
 2325: 		$msgstatus = 
 2326:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
 2327: 						     $message.$messagetail,
 2328:                                                      undef,$feedurl,undef,
 2329:                                                      undef,undef,$showsymb,
 2330:                                                      $restitle);
 2331: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
 2332: 				$msgstatus);
 2333: 	    }
 2334: 	    if ($env{'form.collaborator'.$ctr}) {
 2335: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
 2336: 		foreach my $collabstr (@collabstrs) {
 2337: 		    my ($part,@collaborators) = split(/:/,$collabstr);
 2338: 		    foreach my $collaborator (@collaborators) {
 2339: 			my ($errorflag,$pts,$wgt) = 
 2340: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
 2341: 					   $env{'form.unamedom'.$ctr},$part);
 2342: 			if ($errorflag eq 'not_allowed') {
 2343: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
 2344: 			    next;
 2345: 			} elsif ($message ne '') {
 2346: 			    my ($baseurl,$showsymb) = 
 2347: 				&get_feedurl_and_symb($symb,$collaborator,
 2348: 						      $udom);
 2349: 			    if ($env{'form.withgrades'.$ctr}) {
 2350: 				$messagetail = " for <a href=\"".
 2351:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
 2352: 			    }
 2353: 			    $msgstatus = 
 2354: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
 2355: 			}
 2356: 		    }
 2357: 		}
 2358: 	    }
 2359: 	    $ctr++;
 2360: 	}
 2361:     }
 2362: 
 2363:     if ($env{'form.handgrade'} eq 'yes') {
 2364: 	# Keywords sorted in alphabatical order
 2365: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
 2366: 	my %keyhash = ();
 2367: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
 2368: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
 2369: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
 2370: 	$env{'form.keywords'} = join(' ',@keywords);
 2371: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
 2372: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
 2373: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
 2374: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
 2375: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
 2376: 
 2377: 	# message center - Order of message gets changed. Blank line is eliminated.
 2378: 	# New messages are saved in env for the next student.
 2379: 	# All messages are saved in nohist_handgrade.db
 2380: 	my ($ctr,$idx) = (1,1);
 2381: 	while ($ctr <= $env{'form.savemsgN'}) {
 2382: 	    if ($env{'form.savemsg'.$ctr} ne '') {
 2383: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
 2384: 		$idx++;
 2385: 	    }
 2386: 	    $ctr++;
 2387: 	}
 2388: 	$ctr = 0;
 2389: 	while ($ctr < $ngrade) {
 2390: 	    if ($env{'form.newmsg'.$ctr} ne '') {
 2391: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2392: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
 2393: 		$idx++;
 2394: 	    }
 2395: 	    $ctr++;
 2396: 	}
 2397: 	$env{'form.savemsgN'} = --$idx;
 2398: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
 2399: 	my $putresult = &Apache::lonnet::put
 2400: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
 2401:     }
 2402:     # Called by Save & Refresh from Highlight Attribute Window
 2403:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 2404:     if ($env{'form.refresh'} eq 'on') {
 2405: 	my ($ctr,$total) = (0,0);
 2406: 	while ($ctr < $ngrade) {
 2407: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
 2408: 	    $ctr++;
 2409: 	}
 2410: 	$env{'form.NTSTU'}=$ngrade;
 2411: 	$ctr = 0;
 2412: 	while ($ctr < $total) {
 2413: 	    my $processUser = $env{'form.unamedom'.$ctr};
 2414: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2415: 	    $env{'form.fullname'} = $$fullname{$processUser};
 2416: 	    &submission($request,$ctr,$total-1);
 2417: 	    $ctr++;
 2418: 	}
 2419: 	return '';
 2420:     }
 2421: 
 2422: # Go directly to grade student - from submission or link from chart page
 2423:     if ($button eq 'Grade Student') {
 2424: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
 2425: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
 2426: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
 2427: 	$env{'form.fullname'} = $$fullname{$processUser};
 2428: 	&submission($request,0,0);
 2429: 	return '';
 2430:     }
 2431: 
 2432:     # Get the next/previous one or group of students
 2433:     my $firststu = $env{'form.unamedom0'};
 2434:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
 2435:     my $ctr = 2;
 2436:     while ($laststu eq '') {
 2437: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
 2438: 	$ctr++;
 2439: 	$laststu = $firststu if ($ctr > $ngrade);
 2440:     }
 2441: 
 2442:     my (@parsedlist,@nextlist);
 2443:     my ($nextflg) = 0;
 2444:     foreach (sort 
 2445: 	     {
 2446: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 2447: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 2448: 		 }
 2449: 		 return $a cmp $b;
 2450: 	     } (keys(%$fullname))) {
 2451: 	if ($nextflg == 1 && $button =~ /Next$/) {
 2452: 	    push @parsedlist,$_;
 2453: 	}
 2454: 	$nextflg = 1 if ($_ eq $laststu);
 2455: 	if ($button eq 'Previous') {
 2456: 	    last if ($_ eq $firststu);
 2457: 	    push @parsedlist,$_;
 2458: 	}
 2459:     }
 2460:     $ctr = 0;
 2461:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
 2462:     my ($partlist) = &response_type($symb);
 2463:     foreach my $student (@parsedlist) {
 2464: 	my $submitonly=$env{'form.submitonly'};
 2465: 	my ($uname,$udom) = split(/:/,$student);
 2466: 	
 2467: 	if ($submitonly eq 'queued') {
 2468: 	    my %queue_status = 
 2469: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
 2470: 							$udom,$uname);
 2471: 	    next if (!defined($queue_status{'gradingqueue'}));
 2472: 	}
 2473: 
 2474: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
 2475: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
 2476: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
 2477: 	    my $submitted = 0;
 2478: 	    my $ungraded = 0;
 2479: 	    my $incorrect = 0;
 2480: 	    foreach (keys(%status)) {
 2481: 		$submitted = 1 if ($status{$_} ne 'nothing');
 2482: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
 2483: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
 2484: 		my ($foo,$partid,$foo1) = split(/\./,$_);
 2485: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
 2486: 		    $submitted = 0;
 2487: 		}
 2488: 	    }
 2489: 	    next if (!$submitted && ($submitonly eq 'yes' ||
 2490: 				     $submitonly eq 'incorrect' ||
 2491: 				     $submitonly eq 'graded'));
 2492: 	    next if (!$ungraded && ($submitonly eq 'graded'));
 2493: 	    next if (!$incorrect && $submitonly eq 'incorrect');
 2494: 	}
 2495: 	push @nextlist,$student if ($ctr < $ntstu);
 2496: 	last if ($ctr == $ntstu);
 2497: 	$ctr++;
 2498:     }
 2499: 
 2500:     $ctr = 0;
 2501:     my $total = scalar(@nextlist)-1;
 2502: 
 2503:     foreach (sort @nextlist) {
 2504: 	my ($uname,$udom,$submitter) = split(/:/);
 2505: 	$env{'form.student'}  = $uname;
 2506: 	$env{'form.userdom'}  = $udom;
 2507: 	$env{'form.fullname'} = $$fullname{$_};
 2508: 	&submission($request,$ctr,$total);
 2509: 	$ctr++;
 2510:     }
 2511:     if ($total < 0) {
 2512: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
 2513: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
 2514: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
 2515: 	$the_end.=&show_grading_menu_form($symb);
 2516: 	$request->print($the_end);
 2517:     }
 2518:     return '';
 2519: }
 2520: 
 2521: #---- Save the score and award for each student, if changed
 2522: sub saveHandGrade {
 2523:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
 2524:     my @version_parts;
 2525:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
 2526: 					   $env{'request.course.id'});
 2527:     if (!&canmodify($usec)) { return('not_allowed'); }
 2528:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
 2529:     my @parts_graded;
 2530:     my %newrecord  = ();
 2531:     my ($pts,$wgt) = ('','');
 2532:     my %aggregate = ();
 2533:     my $aggregateflag = 0;
 2534:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
 2535:     foreach my $new_part (@parts) {
 2536: 	#collaborator ($submi may vary for different parts
 2537: 	if ($submitter && $new_part ne $part) { next; }
 2538: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
 2539: 	if ($dropMenu eq 'excused') {
 2540: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
 2541: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
 2542: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
 2543: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
 2544: 		}
 2545: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 2546: 	    }
 2547: 	} elsif ($dropMenu eq 'reset status'
 2548: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
 2549: 	    foreach my $key (keys (%record)) {
 2550: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
 2551: 	    }
 2552: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2553: 		"$env{'user.name'}:$env{'user.domain'}";
 2554:             my $totaltries = $record{'resource.'.$part.'.tries'};
 2555: 
 2556:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
 2557: 					       [$new_part]);
 2558:             my $aggtries =$totaltries;
 2559:             if ($last_resets{$new_part}) {
 2560:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
 2561: 					   $new_part);
 2562:             }
 2563: 
 2564:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
 2565:             if ($aggtries > 0) {
 2566:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 2567:                 $aggregateflag = 1;
 2568:             }
 2569: 	} elsif ($dropMenu eq '') {
 2570: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
 2571: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
 2572: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
 2573: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
 2574: 		next;
 2575: 	    }
 2576: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
 2577: 		$env{'form.WGT'.$newflg.'_'.$new_part};
 2578: 	    my $partial= $pts/$wgt;
 2579: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
 2580: 		#do not update score for part if not changed.
 2581:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
 2582: 		next;
 2583: 	    } else {
 2584: 	        push @parts_graded, $new_part;
 2585: 	    }
 2586: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
 2587: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
 2588: 	    }
 2589: 	    my $reckey = 'resource.'.$new_part.'.solved';
 2590: 	    if ($partial == 0) {
 2591: 		if ($record{$reckey} ne 'incorrect_by_override') {
 2592: 		    $newrecord{$reckey} = 'incorrect_by_override';
 2593: 		}
 2594: 	    } else {
 2595: 		if ($record{$reckey} ne 'correct_by_override') {
 2596: 		    $newrecord{$reckey} = 'correct_by_override';
 2597: 		}
 2598: 	    }	    
 2599: 	    if ($submitter && 
 2600: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
 2601: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
 2602: 	    }
 2603: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
 2604: 		"$env{'user.name'}:$env{'user.domain'}";
 2605: 	}
 2606: 	# unless problem has been graded, set flag to version the submitted files
 2607: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
 2608: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
 2609: 	        $dropMenu eq 'reset status')
 2610: 	   {
 2611: 	    push (@version_parts,$new_part);
 2612: 	}
 2613:     }
 2614:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2615:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2616: 
 2617:     if (%newrecord) {
 2618:         if (@version_parts) {
 2619:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
 2620:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
 2621: 	    @newrecord{@changed_keys} = @record{@changed_keys};
 2622: 	    foreach my $new_part (@version_parts) {
 2623: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
 2624: 				$new_part,\%newrecord);
 2625: 	    }
 2626:         }
 2627: 	&Apache::lonnet::cstore(\%newrecord,$symb,
 2628: 				$env{'request.course.id'},$domain,$stuname);
 2629: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
 2630: 				     $cdom,$cnum,$domain,$stuname);
 2631:     }
 2632:     if ($aggregateflag) {
 2633:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 2634: 			      $cdom,$cnum);
 2635:     }
 2636:     return ('',$pts,$wgt);
 2637: }
 2638: 
 2639: sub check_and_remove_from_queue {
 2640:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
 2641:     my @ungraded_parts;
 2642:     foreach my $part (@{$parts}) {
 2643: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
 2644: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
 2645: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
 2646: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
 2647: 		) {
 2648: 	    push(@ungraded_parts, $part);
 2649: 	}
 2650:     }
 2651:     if ( !@ungraded_parts ) {
 2652: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
 2653: 					       $cnum,$domain,$stuname);
 2654:     }
 2655: }
 2656: 
 2657: sub handback_files {
 2658:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
 2659:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
 2660:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 2661: 
 2662:     my @part_response_id = &flatten_responseType($responseType);
 2663:     foreach my $part_response_id (@part_response_id) {
 2664:     	my ($part_id,$resp_id) = @{ $part_response_id };
 2665: 	my $part_resp = join('_',@{ $part_response_id });
 2666:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
 2667:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
 2668:                 my $file_counter = 1;
 2669: 		my $file_msg;
 2670:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
 2671:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
 2672:                     my ($directory,$answer_file) = 
 2673:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
 2674:                     my ($answer_name,$answer_ver,$answer_ext) =
 2675: 		        &file_name_version_ext($answer_file);
 2676: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
 2677: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
 2678: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2679:                     # fix file name
 2680:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
 2681:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
 2682:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
 2683:             	                                $save_file_name);
 2684:                     if ($result !~ m|^/uploaded/|) {
 2685:                         $request->print('<span class="LC_error">An error occurred ('.$result.
 2686:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
 2687:                     } else {
 2688:                         # mark the file as read only
 2689:                         my @files = ($save_file_name);
 2690:                         my @what = ($symb,$env{'request.course.id'},'handback');
 2691:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
 2692: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
 2693: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
 2694: 			}
 2695:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
 2696: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
 2697: 
 2698:                     }
 2699:                     $request->print("<br />".$fname." will be the uploaded file name");
 2700:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
 2701:                     $file_counter++;
 2702:                 }
 2703: 		my $subject = "File Handed Back by Instructor ";
 2704: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
 2705: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
 2706: 		$message .= ' The returned file(s) are named: '. $file_msg;
 2707: 		$message .= " and can be found in your portfolio space.";
 2708: 		my ($feedurl,$showsymb) = 
 2709: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
 2710:                 my $restitle = &Apache::lonnet::gettitle($symb);
 2711: 		my $msgstatus = 
 2712:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
 2713: 			 ' (File Returned) ['.$restitle.']',$message,undef,
 2714:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
 2715:             }
 2716:         }
 2717:     return;
 2718: }
 2719: 
 2720: sub get_feedurl_and_symb {
 2721:     my ($symb,$uname,$udom) = @_;
 2722:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 2723:     $url = &Apache::lonnet::clutter($url);
 2724:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
 2725: 					$symb,$udom,$uname);
 2726:     if ($encrypturl =~ /^yes$/i) {
 2727: 	&Apache::lonenc::encrypted(\$url,1);
 2728: 	&Apache::lonenc::encrypted(\$symb,1);
 2729:     }
 2730:     return ($url,$symb);
 2731: }
 2732: 
 2733: sub get_submitted_files {
 2734:     my ($udom,$uname,$partid,$respid,$record) = @_;
 2735:     my @files;
 2736:     if ($$record{"resource.$partid.$respid.portfiles"}) {
 2737:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
 2738:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
 2739:     	    push(@files,$file_url.$file);
 2740:         }
 2741:     }
 2742:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
 2743:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
 2744:     }
 2745:     return (\@files);
 2746: }
 2747: 
 2748: # ----------- Provides number of tries since last reset.
 2749: sub get_num_tries {
 2750:     my ($record,$last_reset,$part) = @_;
 2751:     my $timestamp = '';
 2752:     my $num_tries = 0;
 2753:     if ($$record{'version'}) {
 2754:         for (my $version=$$record{'version'};$version>=1;$version--) {
 2755:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
 2756:                 $timestamp = $$record{$version.':timestamp'};
 2757:                 if ($timestamp > $last_reset) {
 2758:                     $num_tries ++;
 2759:                 } else {
 2760:                     last;
 2761:                 }
 2762:             }
 2763:         }
 2764:     }
 2765:     return $num_tries;
 2766: }
 2767: 
 2768: # ----------- Determine decrements required in aggregate totals 
 2769: sub decrement_aggs {
 2770:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
 2771:     my %decrement = (
 2772:                         attempts => 0,
 2773:                         users => 0,
 2774:                         correct => 0
 2775:                     );
 2776:     $decrement{'attempts'} = $aggtries;
 2777:     if ($solvedstatus =~ /^correct/) {
 2778:         $decrement{'correct'} = 1;
 2779:     }
 2780:     if ($aggtries == $totaltries) {
 2781:         $decrement{'users'} = 1;
 2782:     }
 2783:     foreach my $type (keys (%decrement)) {
 2784:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
 2785:     }
 2786:     return;
 2787: }
 2788: 
 2789: # ----------- Determine timestamps for last reset of aggregate totals for parts  
 2790: sub get_last_resets {
 2791:     my ($symb,$courseid,$partids) =@_;
 2792:     my %last_resets;
 2793:     my $cdom = $env{'course.'.$courseid.'.domain'};
 2794:     my $cname = $env{'course.'.$courseid.'.num'};
 2795:     my @keys;
 2796:     foreach my $part (@{$partids}) {
 2797: 	push(@keys,"$symb\0$part\0resettime");
 2798:     }
 2799:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
 2800: 				     $cdom,$cname);
 2801:     foreach my $part (@{$partids}) {
 2802: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
 2803:     }
 2804:     return %last_resets;
 2805: }
 2806: 
 2807: # ----------- Handles creating versions for portfolio files as answers
 2808: sub version_portfiles {
 2809:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
 2810:     my $version_parts = join('|',@$v_flag);
 2811:     my @returned_keys;
 2812:     my $parts = join('|', @$parts_graded);
 2813:     my $portfolio_root = &propath($domain,$stu_name).
 2814: 	'/userfiles/portfolio';
 2815:     foreach my $key (keys(%$record)) {
 2816:         my $new_portfiles;
 2817:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
 2818:             my @versioned_portfiles;
 2819:             my @portfiles = split(/\s*,\s*/,$$record{$key});
 2820:             foreach my $file (@portfiles) {
 2821:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 2822:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 2823: 		my ($answer_name,$answer_ver,$answer_ext) =
 2824: 		    &file_name_version_ext($answer_file);
 2825:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
 2826:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
 2827:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
 2828:                 if ($new_answer ne 'problem getting file') {
 2829:                     push(@versioned_portfiles, $directory.$new_answer);
 2830:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
 2831:                         [$directory.$new_answer],
 2832:                         [$symb,$env{'request.course.id'},'graded']);
 2833:                 }
 2834:             }
 2835:             $$record{$key} = join(',',@versioned_portfiles);
 2836:             push(@returned_keys,$key);
 2837:         }
 2838:     } 
 2839:     return (@returned_keys);   
 2840: }
 2841: 
 2842: sub get_next_version {
 2843:     my ($answer_name, $answer_ext, $dir_list) = @_;
 2844:     my $version;
 2845:     foreach my $row (@$dir_list) {
 2846:         my ($file) = split(/\&/,$row,2);
 2847:         my ($file_name,$file_version,$file_ext) =
 2848: 	    &file_name_version_ext($file);
 2849:         if (($file_name eq $answer_name) && 
 2850: 	    ($file_ext eq $answer_ext)) {
 2851:                 # gets here if filename and extension match, regardless of version
 2852:                 if ($file_version ne '') {
 2853:                 # a versioned file is found  so save it for later
 2854:                 if ($file_version > $version) {
 2855: 		    $version = $file_version;
 2856: 	        }
 2857:             }
 2858:         }
 2859:     } 
 2860:     $version ++;
 2861:     return($version);
 2862: }
 2863: 
 2864: sub version_selected_portfile {
 2865:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 2866:     my ($answer_name,$answer_ver,$answer_ext) =
 2867:         &file_name_version_ext($file_name);
 2868:     my $new_answer;
 2869:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 2870:     if($env{'form.copy'} eq '-1') {
 2871:         $new_answer = 'problem getting file';
 2872:     } else {
 2873:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 2874:         my $copy_result = &Apache::lonnet::finishuserfileupload(
 2875:                             $stu_name,$domain,'copy',
 2876: 		        '/portfolio'.$directory.$new_answer);
 2877:     }    
 2878:     return ($new_answer);
 2879: }
 2880: 
 2881: sub file_name_version_ext {
 2882:     my ($file)=@_;
 2883:     my @file_parts = split(/\./, $file);
 2884:     my ($name,$version,$ext);
 2885:     if (@file_parts > 1) {
 2886: 	$ext=pop(@file_parts);
 2887: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 2888: 	    $version=pop(@file_parts);
 2889: 	}
 2890: 	$name=join('.',@file_parts);
 2891:     } else {
 2892: 	$name=join('.',@file_parts);
 2893:     }
 2894:     return($name,$version,$ext);
 2895: }
 2896: 
 2897: #--------------------------------------------------------------------------------------
 2898: #
 2899: #-------------------------- Next few routines handles grading by section or whole class
 2900: #
 2901: #--- Javascript to handle grading by section or whole class
 2902: sub viewgrades_js {
 2903:     my ($request) = shift;
 2904: 
 2905:     $request->print(<<VIEWJAVASCRIPT);
 2906: <script type="text/javascript" language="javascript">
 2907:    function writePoint(partid,weight,point) {
 2908: 	var radioButton = document.classgrade["RADVAL_"+partid];
 2909: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 2910: 	if (point == "textval") {
 2911: 	    point = document.classgrade["TEXTVAL_"+partid].value;
 2912: 	    if (isNaN(point) || parseFloat(point) < 0) {
 2913: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 2914: 		var resetbox = false;
 2915: 		for (var i=0; i<radioButton.length; i++) {
 2916: 		    if (radioButton[i].checked) {
 2917: 			textbox.value = i;
 2918: 			resetbox = true;
 2919: 		    }
 2920: 		}
 2921: 		if (!resetbox) {
 2922: 		    textbox.value = "";
 2923: 		}
 2924: 		return;
 2925: 	    }
 2926: 	    if (parseFloat(point) > parseFloat(weight)) {
 2927: 		var resp = confirm("You entered a value ("+parseFloat(point)+
 2928: 				   ") greater than the weight for the part. Accept?");
 2929: 		if (resp == false) {
 2930: 		    textbox.value = "";
 2931: 		    return;
 2932: 		}
 2933: 	    }
 2934: 	    for (var i=0; i<radioButton.length; i++) {
 2935: 		radioButton[i].checked=false;
 2936: 		if (parseFloat(point) == i) {
 2937: 		    radioButton[i].checked=true;
 2938: 		}
 2939: 	    }
 2940: 
 2941: 	} else {
 2942: 	    textbox.value = parseFloat(point);
 2943: 	}
 2944: 	for (i=0;i<document.classgrade.total.value;i++) {
 2945: 	    var user = document.classgrade["ctr"+i].value;
 2946: 	    user = user.replace(new RegExp(':', 'g'),"_");
 2947: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 2948: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 2949: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 2950: 	    if (saveval != "correct") {
 2951: 		scorename.value = point;
 2952: 		if (selname[0].selected != true) {
 2953: 		    selname[0].selected = true;
 2954: 		}
 2955: 	    }
 2956: 	}
 2957: 	document.classgrade["SELVAL_"+partid][0].selected = true;
 2958:     }
 2959: 
 2960:     function writeRadText(partid,weight) {
 2961: 	var selval   = document.classgrade["SELVAL_"+partid];
 2962: 	var radioButton = document.classgrade["RADVAL_"+partid];
 2963:         var override = document.classgrade["FORCE_"+partid].checked;
 2964: 	var textbox = document.classgrade["TEXTVAL_"+partid];
 2965: 	if (selval[1].selected || selval[2].selected) {
 2966: 	    for (var i=0; i<radioButton.length; i++) {
 2967: 		radioButton[i].checked=false;
 2968: 
 2969: 	    }
 2970: 	    textbox.value = "";
 2971: 
 2972: 	    for (i=0;i<document.classgrade.total.value;i++) {
 2973: 		var user = document.classgrade["ctr"+i].value;
 2974: 		user = user.replace(new RegExp(':', 'g'),"_");
 2975: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 2976: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 2977: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 2978: 		if ((saveval != "correct") || override) {
 2979: 		    scorename.value = "";
 2980: 		    if (selval[1].selected) {
 2981: 			selname[1].selected = true;
 2982: 		    } else {
 2983: 			selname[2].selected = true;
 2984: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
 2985: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
 2986: 		    }
 2987: 		}
 2988: 	    }
 2989: 	} else {
 2990: 	    for (i=0;i<document.classgrade.total.value;i++) {
 2991: 		var user = document.classgrade["ctr"+i].value;
 2992: 		user = user.replace(new RegExp(':', 'g'),"_");
 2993: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 2994: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 2995: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 2996: 		if ((saveval != "correct") || override) {
 2997: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 2998: 		    selname[0].selected = true;
 2999: 		}
 3000: 	    }
 3001: 	}	    
 3002:     }
 3003: 
 3004:     function changeSelect(partid,user) {
 3005: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3006: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
 3007: 	var point  = textbox.value;
 3008: 	var weight = document.classgrade["weight_"+partid].value;
 3009: 
 3010: 	if (isNaN(point) || parseFloat(point) < 0) {
 3011: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
 3012: 	    textbox.value = "";
 3013: 	    return;
 3014: 	}
 3015: 	if (parseFloat(point) > parseFloat(weight)) {
 3016: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
 3017: 			       ") greater than the weight of the part. Accept?");
 3018: 	    if (resp == false) {
 3019: 		textbox.value = "";
 3020: 		return;
 3021: 	    }
 3022: 	}
 3023: 	selval[0].selected = true;
 3024:     }
 3025: 
 3026:     function changeOneScore(partid,user) {
 3027: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
 3028: 	if (selval[1].selected || selval[2].selected) {
 3029: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
 3030: 	    if (selval[2].selected) {
 3031: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
 3032: 	    }
 3033:         }
 3034:     }
 3035: 
 3036:     function resetEntry(numpart) {
 3037: 	for (ctpart=0;ctpart<numpart;ctpart++) {
 3038: 	    var partid = document.classgrade["partid_"+ctpart].value;
 3039: 	    var radioButton = document.classgrade["RADVAL_"+partid];
 3040: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
 3041: 	    var selval  = document.classgrade["SELVAL_"+partid];
 3042: 	    for (var i=0; i<radioButton.length; i++) {
 3043: 		radioButton[i].checked=false;
 3044: 
 3045: 	    }
 3046: 	    textbox.value = "";
 3047: 	    selval[0].selected = true;
 3048: 
 3049: 	    for (i=0;i<document.classgrade.total.value;i++) {
 3050: 		var user = document.classgrade["ctr"+i].value;
 3051: 		user = user.replace(new RegExp(':', 'g'),"_");
 3052: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
 3053: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
 3054: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
 3055: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
 3056: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
 3057: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
 3058: 		if (saveselval == "excused") {
 3059: 		    if (selname[1].selected == false) { selname[1].selected = true;}
 3060: 		} else {
 3061: 		    if (selname[0].selected == false) {selname[0].selected = true};
 3062: 		}
 3063: 	    }
 3064: 	}
 3065:     }
 3066: 
 3067: </script>
 3068: VIEWJAVASCRIPT
 3069: }
 3070: 
 3071: #--- show scores for a section or whole class w/ option to change/update a score
 3072: sub viewgrades {
 3073:     my ($request) = shift;
 3074:     &viewgrades_js($request);
 3075: 
 3076:     my ($symb) = &get_symb($request);
 3077:     #need to make sure we have the correct data for later EXT calls, 
 3078:     #thus invalidate the cache
 3079:     &Apache::lonnet::devalidatecourseresdata(
 3080:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 3081:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 3082:     &Apache::lonnet::clear_EXT_cache_status();
 3083: 
 3084:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
 3085:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
 3086: 
 3087:     #view individual student submission form - called using Javascript viewOneStudent
 3088:     $result.=&jscriptNform($symb);
 3089: 
 3090:     #beginning of class grading form
 3091:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 3092:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
 3093: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 3094: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 3095: 	&build_section_inputs().
 3096: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 3097: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
 3098: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 3099: 
 3100:     my $sectionClass;
 3101:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3102:     if ($env{'form.section'} eq 'all') {
 3103: 	$sectionClass='Class </h3>';
 3104:     } elsif ($env{'form.section'} eq 'none') {
 3105: 	$sectionClass=&mt('Students in no Section').'</h3>';
 3106:     } else {
 3107: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
 3108:     }
 3109:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
 3110:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
 3111: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
 3112:     #radio buttons/text box for assigning points for a section or class.
 3113:     #handles different parts of a problem
 3114:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 3115:     my %weight = ();
 3116:     my $ctsparts = 0;
 3117:     $result.='<table border="0">';
 3118:     my %seen = ();
 3119:     my @part_response_id = &flatten_responseType($responseType);
 3120:     foreach my $part_response_id (@part_response_id) {
 3121:     	my ($partid,$respid) = @{ $part_response_id };
 3122: 	my $part_resp = join('_',@{ $part_response_id });
 3123: 	next if $seen{$partid};
 3124: 	$seen{$partid}++;
 3125: 	my $handgrade=$$handgrade{$part_resp};
 3126: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
 3127: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
 3128: 
 3129: 	$result.='<input type="hidden" name="partid_'.
 3130: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
 3131: 	$result.='<input type="hidden" name="weight_'.
 3132: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
 3133: 	my $display_part=&get_display_part($partid,$symb);
 3134: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
 3135: 	$result.='<table border="0"><tr>';  
 3136: 	my $ctr = 0;
 3137: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
 3138: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
 3139: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
 3140: 		','.$ctr.')" />'.$ctr."</label></td>\n";
 3141: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
 3142: 	    $ctr++;
 3143: 	}
 3144: 	$result.='</tr></table>';
 3145: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
 3146: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
 3147: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
 3148: 	    $weight{$partid}.' (problem weight)</td>'."\n";
 3149: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
 3150: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
 3151: 		$weight{$partid}.')"> '.
 3152: 	    '<option selected="selected"> </option>'.
 3153: 	    '<option>excused</option>'.
 3154: 	    '<option>reset status</option></select></td>'.
 3155:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
 3156: 	$ctsparts++;
 3157:     }
 3158:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
 3159: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
 3160:     $result.='<input type="button" value="Revert to Default" '.
 3161: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
 3162: 
 3163:     #table listing all the students in a section/class
 3164:     #header of table
 3165:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
 3166:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
 3167: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
 3168: 	'<td>'.&nameUserString('header')."</td>\n";
 3169:     my (@parts) = sort(&getpartlist($symb));
 3170:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
 3171:     my @partids = ();
 3172:     foreach my $part (@parts) {
 3173: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3174: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
 3175: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
 3176: 	my ($partid) = &split_part_type($part);
 3177:         push(@partids, $partid);
 3178: 	my $display_part=&get_display_part($partid,$symb);
 3179: 	if ($display =~ /^Partial Credit Factor/) {
 3180: 	    $result.='<td><b>Score Part:</b> '.$display_part.
 3181: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
 3182: 	    next;
 3183: 	} else {
 3184: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
 3185: 	}
 3186: 	$display =~ s|Problem Status|Grade Status<br />|;
 3187: 	$result.='<td><b>'.$display.'</td>'."\n";
 3188:     }
 3189:     $result.='</tr>';
 3190: 
 3191:     my %last_resets = 
 3192: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
 3193: 
 3194:     #get info for each student
 3195:     #list all the students - with points and grade status
 3196:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
 3197:     my $ctr = 0;
 3198:     foreach (sort 
 3199: 	     {
 3200: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 3201: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 3202: 		 }
 3203: 		 return $a cmp $b;
 3204: 	     } (keys(%$fullname))) {
 3205: 	$ctr++;
 3206: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
 3207: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
 3208:     }
 3209:     $result.='</table></td></tr></table>';
 3210:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
 3211:     $result.='<input type="button" value="Save" '.
 3212: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
 3213:     if (scalar(%$fullname) eq 0) {
 3214: 	my $colspan=3+scalar(@parts);
 3215: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3216:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
 3217: 	$result='<span class="LC_warning">'.
 3218: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
 3219: 	        $section_display, $stu_status).
 3220: 	    '</span>';
 3221:     }
 3222:     $result.=&show_grading_menu_form($symb);
 3223:     return $result;
 3224: }
 3225: 
 3226: #--- call by previous routine to display each student
 3227: sub viewstudentgrade {
 3228:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
 3229:     my ($uname,$udom) = split(/:/,$student);
 3230:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
 3231:     my %aggregates = (); 
 3232:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
 3233: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
 3234: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
 3235: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
 3236: 	'\');" target="_self">'.$fullname.'</a> '.
 3237: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
 3238:     $student=~s/:/_/; # colon doen't work in javascript for names
 3239:     foreach my $apart (@$parts) {
 3240: 	my ($part,$type) = &split_part_type($apart);
 3241: 	my $score=$record{"resource.$part.$type"};
 3242:         $result.='<td align="center">';
 3243:         my ($aggtries,$totaltries);
 3244:         unless (exists($aggregates{$part})) {
 3245: 	    $totaltries = $record{'resource.'.$part.'.tries'};
 3246: 
 3247: 	    $aggtries = $totaltries;
 3248:             if ($$last_resets{$part}) {  
 3249:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
 3250: 					   $part);
 3251:             }
 3252:             $result.='<input type="hidden" name="'.
 3253:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
 3254:             $result.='<input type="hidden" name="'.
 3255:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
 3256:             $aggregates{$part} = 1;
 3257:         }
 3258: 	if ($type eq 'awarded') {
 3259: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
 3260: 	    $result.='<input type="hidden" name="'.
 3261: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 3262: 	    $result.='<input type="text" name="'.
 3263: 		'GD_'.$student.'_'.$part.'_awarded" '.
 3264: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 3265: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 3266: 	} elsif ($type eq 'solved') {
 3267: 	    my ($status,$foo)=split(/_/,$score,2);
 3268: 	    $status = 'nothing' if ($status eq '');
 3269: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 3270: 		$part.'_solved_s" value="'.$status.'" />'."\n";
 3271: 	    $result.='&nbsp;<select name="'.
 3272: 		'GD_'.$student.'_'.$part.'_solved" '.
 3273: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 3274: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
 3275: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
 3276: 	    $result.='<option>reset status</option>';
 3277: 	    $result.="</select>&nbsp;</td>\n";
 3278: 	} else {
 3279: 	    $result.='<input type="hidden" name="'.
 3280: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 3281: 		    "\n";
 3282: 	    $result.='<input type="text" name="'.
 3283: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 3284: 		'value="'.$score.'" size="4" /></td>'."\n";
 3285: 	}
 3286:     }
 3287:     $result.='</tr>';
 3288:     return $result;
 3289: }
 3290: 
 3291: #--- change scores for all the students in a section/class
 3292: #    record does not get update if unchanged
 3293: sub editgrades {
 3294:     my ($request) = @_;
 3295: 
 3296:     my $symb=&get_symb($request);
 3297:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
 3298:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
 3299:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
 3300:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
 3301: 
 3302:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
 3303:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
 3304: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
 3305: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
 3306: 
 3307:     my %scoreptr = (
 3308: 		    'correct'  =>'correct_by_override',
 3309: 		    'incorrect'=>'incorrect_by_override',
 3310: 		    'excused'  =>'excused',
 3311: 		    'ungraded' =>'ungraded_attempted',
 3312: 		    'nothing'  => '',
 3313: 		    );
 3314:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
 3315: 
 3316:     my (@partid);
 3317:     my %weight = ();
 3318:     my %columns = ();
 3319:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
 3320: 
 3321:     my (@parts) = sort(&getpartlist($symb));
 3322:     my $header;
 3323:     while ($ctr < $env{'form.totalparts'}) {
 3324: 	my $partid = $env{'form.partid_'.$ctr};
 3325: 	push @partid,$partid;
 3326: 	$weight{$partid} = $env{'form.weight_'.$partid};
 3327: 	$ctr++;
 3328:     }
 3329:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3330:     foreach my $partid (@partid) {
 3331: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
 3332: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
 3333: 	$columns{$partid}=2;
 3334: 	foreach my $stores (@parts) {
 3335: 	    my ($part,$type) = &split_part_type($stores);
 3336: 	    if ($part !~ m/^\Q$partid\E/) { next;}
 3337: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
 3338: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
 3339: 	    $display =~ s/\[Part: (\w)+\]//;
 3340: 	    $display =~ s/Number of Attempts/Tries/;
 3341: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
 3342: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
 3343: 	    $columns{$partid}+=2;
 3344: 	}
 3345:     }
 3346:     foreach my $partid (@partid) {
 3347: 	my $display_part=&get_display_part($partid,$symb);
 3348: 	$result .= '<td colspan="'.$columns{$partid}.
 3349: 	    '" align="center"><b>Part:</b> '.$display_part.
 3350: 	    ' (Weight = '.$weight{$partid}.')</td>';
 3351: 
 3352:     }
 3353:     $result .= '</tr><tr bgcolor="#deffff">';
 3354:     $result .= $header;
 3355:     $result .= '</tr>'."\n";
 3356:     my $noupdate;
 3357:     my ($updateCtr,$noupdateCtr) = (1,1);
 3358:     for ($i=0; $i<$env{'form.total'}; $i++) {
 3359: 	my $line;
 3360: 	my $user = $env{'form.ctr'.$i};
 3361: 	my ($uname,$udom)=split(/:/,$user);
 3362: 	my %newrecord;
 3363: 	my $updateflag = 0;
 3364: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
 3365: 	my $usec=$classlist->{"$uname:$udom"}[5];
 3366: 	if (!&canmodify($usec)) {
 3367: 	    my $numcols=scalar(@partid)*4+2;
 3368: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
 3369: 	    next;
 3370: 	}
 3371:         my %aggregate = ();
 3372:         my $aggregateflag = 0;
 3373: 	$user=~s/:/_/; # colon doen't work in javascript for names
 3374: 	foreach (@partid) {
 3375: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 3376: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
 3377: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
 3378: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3379: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
 3380: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
 3381: 	    my $partial   = $awarded eq '' ? '' : $pcr;
 3382: 	    my $score;
 3383: 	    if ($partial eq '') {
 3384: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
 3385: 	    } elsif ($partial > 0) {
 3386: 		$score = 'correct_by_override';
 3387: 	    } elsif ($partial == 0) {
 3388: 		$score = 'incorrect_by_override';
 3389: 	    }
 3390: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
 3391: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
 3392: 
 3393: 	    $newrecord{'resource.'.$_.'.regrader'}=
 3394: 		"$env{'user.name'}:$env{'user.domain'}";
 3395: 	    if ($dropMenu eq 'reset status' &&
 3396: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
 3397: 		$newrecord{'resource.'.$_.'.tries'} = '';
 3398: 		$newrecord{'resource.'.$_.'.solved'} = '';
 3399: 		$newrecord{'resource.'.$_.'.award'} = '';
 3400: 		$newrecord{'resource.'.$_.'.awarded'} = '';
 3401: 		$updateflag = 1;
 3402:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
 3403:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
 3404:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
 3405:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
 3406:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 3407:                     $aggregateflag = 1;
 3408:                 }
 3409: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
 3410: 		$updateflag = 1;
 3411: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
 3412: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
 3413: 		$rec_update++;
 3414: 	    }
 3415: 
 3416: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3417: 		'<td align="center">'.$awarded.
 3418: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
 3419: 
 3420: 
 3421: 	    my $partid=$_;
 3422: 	    foreach my $stores (@parts) {
 3423: 		my ($part,$type) = &split_part_type($stores);
 3424: 		if ($part !~ m/^\Q$partid\E/) { next;}
 3425: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
 3426: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
 3427: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
 3428: 		if ($awarded ne '' && $awarded ne $old_aw) {
 3429: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
 3430: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
 3431: 		    $updateflag=1;
 3432: 		}
 3433: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
 3434: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
 3435: 	    }
 3436: 	}
 3437: 	$line.='</tr>'."\n";
 3438: 
 3439: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3440: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3441: 
 3442: 	if ($updateflag) {
 3443: 	    $count++;
 3444: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
 3445: 				    $udom,$uname);
 3446: 
 3447: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
 3448: 					      $cnum,$udom,$uname)) {
 3449: 		# need to figure out if should be in queue.
 3450: 		my %record =  
 3451: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
 3452: 					     $udom,$uname);
 3453: 		my $all_graded = 1;
 3454: 		my $none_graded = 1;
 3455: 		foreach my $part (@parts) {
 3456: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
 3457: 			$all_graded = 0;
 3458: 		    } else {
 3459: 			$none_graded = 0;
 3460: 		    }
 3461: 		}
 3462: 
 3463: 		if ($all_graded || $none_graded) {
 3464: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
 3465: 							   $symb,$cdom,$cnum,
 3466: 							   $udom,$uname);
 3467: 		}
 3468: 	    }
 3469: 
 3470: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
 3471: 	    $updateCtr++;
 3472: 	} else {
 3473: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
 3474: 	    $noupdateCtr++;
 3475: 	}
 3476:         if ($aggregateflag) {
 3477:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 3478: 				  $cdom,$cnum);
 3479:         }
 3480:     }
 3481:     if ($noupdate) {
 3482: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
 3483: 	my $numcols=scalar(@partid)*4+2;
 3484: 	$result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr><tr bgcolor="#ffffde">'.$noupdate;
 3485:     }
 3486:     $result .= '</table></td></tr></table>'."\n".
 3487: 	&show_grading_menu_form ($symb);
 3488:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
 3489: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
 3490: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
 3491:     return $title.$msg.$result;
 3492: }
 3493: 
 3494: sub split_part_type {
 3495:     my ($partstr) = @_;
 3496:     my ($temp,@allparts)=split(/_/,$partstr);
 3497:     my $type=pop(@allparts);
 3498:     my $part=join('_',@allparts);
 3499:     return ($part,$type);
 3500: }
 3501: 
 3502: #------------- end of section for handling grading by section/class ---------
 3503: #
 3504: #----------------------------------------------------------------------------
 3505: 
 3506: 
 3507: #----------------------------------------------------------------------------
 3508: #
 3509: #-------------------------- Next few routines handles grading by csv upload
 3510: #
 3511: #--- Javascript to handle csv upload
 3512: sub csvupload_javascript_reverse_associate {
 3513:     my $error1=&mt('You need to specify the username or ID');
 3514:     my $error2=&mt('You need to specify at least one grading field');
 3515:   return(<<ENDPICK);
 3516:   function verify(vf) {
 3517:     var foundsomething=0;
 3518:     var founduname=0;
 3519:     var foundID=0;
 3520:     for (i=0;i<=vf.nfields.value;i++) {
 3521:       tw=eval('vf.f'+i+'.selectedIndex');
 3522:       if (i==0 && tw!=0) { foundID=1; }
 3523:       if (i==1 && tw!=0) { founduname=1; }
 3524:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
 3525:     }
 3526:     if (founduname==0 && foundID==0) {
 3527: 	alert('$error1');
 3528: 	return;
 3529:     }
 3530:     if (foundsomething==0) {
 3531: 	alert('$error2');
 3532: 	return;
 3533:     }
 3534:     vf.submit();
 3535:   }
 3536:   function flip(vf,tf) {
 3537:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3538:     var i;
 3539:     for (i=0;i<=vf.nfields.value;i++) {
 3540:       //can not pick the same destination field for both name and domain
 3541:       if (((i ==0)||(i ==1)) && 
 3542:           ((tf==0)||(tf==1)) && 
 3543:           (i!=tf) &&
 3544:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3545:         eval('vf.f'+i+'.selectedIndex=0;')
 3546:       }
 3547:     }
 3548:   }
 3549: ENDPICK
 3550: }
 3551: 
 3552: sub csvupload_javascript_forward_associate {
 3553:     my $error1=&mt('You need to specify the username or ID');
 3554:     my $error2=&mt('You need to specify at least one grading field');
 3555:   return(<<ENDPICK);
 3556:   function verify(vf) {
 3557:     var foundsomething=0;
 3558:     var founduname=0;
 3559:     var foundID=0;
 3560:     for (i=0;i<=vf.nfields.value;i++) {
 3561:       tw=eval('vf.f'+i+'.selectedIndex');
 3562:       if (tw==1) { foundID=1; }
 3563:       if (tw==2) { founduname=1; }
 3564:       if (tw>3) { foundsomething=1; }
 3565:     }
 3566:     if (founduname==0 && foundID==0) {
 3567: 	alert('$error1');
 3568: 	return;
 3569:     }
 3570:     if (foundsomething==0) {
 3571: 	alert('$error2');
 3572: 	return;
 3573:     }
 3574:     vf.submit();
 3575:   }
 3576:   function flip(vf,tf) {
 3577:     var nw=eval('vf.f'+tf+'.selectedIndex');
 3578:     var i;
 3579:     //can not pick the same destination field twice
 3580:     for (i=0;i<=vf.nfields.value;i++) {
 3581:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 3582:         eval('vf.f'+i+'.selectedIndex=0;')
 3583:       }
 3584:     }
 3585:   }
 3586: ENDPICK
 3587: }
 3588: 
 3589: sub csvuploadmap_header {
 3590:     my ($request,$symb,$datatoken,$distotal)= @_;
 3591:     my $javascript;
 3592:     if ($env{'form.upfile_associate'} eq 'reverse') {
 3593: 	$javascript=&csvupload_javascript_reverse_associate();
 3594:     } else {
 3595: 	$javascript=&csvupload_javascript_forward_associate();
 3596:     }
 3597: 
 3598:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 3599:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
 3600:     my $ignore=&mt('Ignore First Line');
 3601:     $symb = &Apache::lonenc::check_encrypt($symb);
 3602:     $request->print(<<ENDPICK);
 3603: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3604: <h3><span class="LC_info">Uploading Class Grades</span></h3>
 3605: $result
 3606: <hr />
 3607: <h3>Identify fields</h3>
 3608: Total number of records found in file: $distotal <hr />
 3609: Enter as many fields as you can. The system will inform you and bring you back
 3610: to this page if the data selected is insufficient to run your class.<hr />
 3611: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
 3612: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
 3613: <input type="hidden" name="associate"  value="" />
 3614: <input type="hidden" name="phase"      value="three" />
 3615: <input type="hidden" name="datatoken"  value="$datatoken" />
 3616: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
 3617: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
 3618: <input type="hidden" name="upfile_associate" 
 3619:                                        value="$env{'form.upfile_associate'}" />
 3620: <input type="hidden" name="symb"       value="$symb" />
 3621: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3622: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
 3623: <input type="hidden" name="command"    value="csvuploadoptions" />
 3624: <hr />
 3625: <script type="text/javascript" language="Javascript">
 3626: $javascript
 3627: </script>
 3628: ENDPICK
 3629:     return '';
 3630: 
 3631: }
 3632: 
 3633: sub csvupload_fields {
 3634:     my ($symb) = @_;
 3635:     my (@parts) = &getpartlist($symb);
 3636:     my @fields=(['ID','Student ID'],
 3637: 		['username','Student Username'],
 3638: 		['domain','Student Domain']);
 3639:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
 3640:     foreach my $part (sort(@parts)) {
 3641: 	my @datum;
 3642: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
 3643: 	my $name=$part;
 3644: 	if  (!$display) { $display = $name; }
 3645: 	@datum=($name,$display);
 3646: 	if ($name=~/^stores_(.*)_awarded/) {
 3647: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
 3648: 	}
 3649: 	push(@fields,\@datum);
 3650:     }
 3651:     return (@fields);
 3652: }
 3653: 
 3654: sub csvuploadmap_footer {
 3655:     my ($request,$i,$keyfields) =@_;
 3656:     $request->print(<<ENDPICK);
 3657: </table>
 3658: <input type="hidden" name="nfields" value="$i" />
 3659: <input type="hidden" name="keyfields" value="$keyfields" />
 3660: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
 3661: </form>
 3662: ENDPICK
 3663: }
 3664: 
 3665: sub checkforfile_js {
 3666:     my $result =<<CSVFORMJS;
 3667: <script type="text/javascript" language="javascript">
 3668:     function checkUpload(formname) {
 3669: 	if (formname.upfile.value == "") {
 3670: 	    alert("Please use the browse button to select a file from your local directory.");
 3671: 	    return false;
 3672: 	}
 3673: 	formname.submit();
 3674:     }
 3675:     </script>
 3676: CSVFORMJS
 3677:     return $result;
 3678: }
 3679: 
 3680: sub upcsvScores_form {
 3681:     my ($request) = shift;
 3682:     my ($symb)=&get_symb($request);
 3683:     if (!$symb) {return '';}
 3684:     my $result=&checkforfile_js();
 3685:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 3686:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 3687:     $result.=$table;
 3688:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 3689:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 3690:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
 3691: 	'.</b></td></tr>'."\n";
 3692:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 3693:     my $upload=&mt("Upload Scores");
 3694:     my $upfile_select=&Apache::loncommon::upfile_select_html();
 3695:     my $ignore=&mt('Ignore First Line');
 3696:     $symb = &Apache::lonenc::check_encrypt($symb);
 3697:     $result.=<<ENDUPFORM;
 3698: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3699: <input type="hidden" name="symb" value="$symb" />
 3700: <input type="hidden" name="command" value="csvuploadmap" />
 3701: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 3702: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 3703: $upfile_select
 3704: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 3705: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
 3706: </form>
 3707: ENDUPFORM
 3708:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 3709:                            &mt("How do I create a CSV file from a spreadsheet"))
 3710:     .'</td></tr></table>'."\n";
 3711:     $result.='</td></tr></table><br /><br />'."\n";
 3712:     $result.=&show_grading_menu_form($symb);
 3713:     return $result;
 3714: }
 3715: 
 3716: 
 3717: sub csvuploadmap {
 3718:     my ($request)= @_;
 3719:     my ($symb)=&get_symb($request);
 3720:     if (!$symb) {return '';}
 3721: 
 3722:     my $datatoken;
 3723:     if (!$env{'form.datatoken'}) {
 3724: 	$datatoken=&Apache::loncommon::upfile_store($request);
 3725:     } else {
 3726: 	$datatoken=$env{'form.datatoken'};
 3727: 	&Apache::loncommon::load_tmp_file($request);
 3728:     }
 3729:     my @records=&Apache::loncommon::upfile_record_sep();
 3730:     if ($env{'form.noFirstLine'}) { shift(@records); }
 3731:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
 3732:     my ($i,$keyfields);
 3733:     if (@records) {
 3734: 	my @fields=&csvupload_fields($symb);
 3735: 
 3736: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
 3737: 	    &Apache::loncommon::csv_print_samples($request,\@records);
 3738: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
 3739: 							  \@fields);
 3740: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
 3741: 	    chop($keyfields);
 3742: 	} else {
 3743: 	    unshift(@fields,['none','']);
 3744: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
 3745: 							    \@fields);
 3746:             foreach my $rec (@records) {
 3747:                 my %temp = &Apache::loncommon::record_sep($rec);
 3748:                 if (%temp) {
 3749:                     $keyfields=join(',',sort(keys(%temp)));
 3750:                     last;
 3751:                 }
 3752:             }
 3753: 	}
 3754:     }
 3755:     &csvuploadmap_footer($request,$i,$keyfields);
 3756:     $request->print(&show_grading_menu_form($symb));
 3757: 
 3758:     return '';
 3759: }
 3760: 
 3761: sub csvuploadoptions {
 3762:     my ($request)= @_;
 3763:     my ($symb)=&get_symb($request);
 3764:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
 3765:     my $ignore=&mt('Ignore First Line');
 3766:     $request->print(<<ENDPICK);
 3767: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 3768: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
 3769: <input type="hidden" name="command"    value="csvuploadassign" />
 3770: <!--
 3771: <p>
 3772: <label>
 3773:    <input type="checkbox" name="show_full_results" />
 3774:    Show a table of all changes
 3775: </label>
 3776: </p>
 3777: -->
 3778: <p>
 3779: <label>
 3780:    <input type="checkbox" name="overwite_scores" checked="checked" />
 3781:    Overwrite any existing score
 3782: </label>
 3783: </p>
 3784: ENDPICK
 3785:     my %fields=&get_fields();
 3786:     if (!defined($fields{'domain'})) {
 3787: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
 3788: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
 3789:     }
 3790:     foreach my $key (sort(keys(%env))) {
 3791: 	if ($key !~ /^form\.(.*)$/) { next; }
 3792: 	my $cleankey=$1;
 3793: 	if ($cleankey eq 'command') { next; }
 3794: 	$request->print('<input type="hidden" name="'.$cleankey.
 3795: 			'"  value="'.$env{$key}.'" />'."\n");
 3796:     }
 3797:     # FIXME do a check for any duplicated user ids...
 3798:     # FIXME do a check for any invalid user ids?...
 3799:     $request->print('<input type="submit" value="Assign Grades" /><br />
 3800: <hr /></form>'."\n");
 3801:     $request->print(&show_grading_menu_form($symb));
 3802:     return '';
 3803: }
 3804: 
 3805: sub get_fields {
 3806:     my %fields;
 3807:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 3808:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 3809: 	if ($env{'form.upfile_associate'} eq 'reverse') {
 3810: 	    if ($env{'form.f'.$i} ne 'none') {
 3811: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
 3812: 	    }
 3813: 	} else {
 3814: 	    if ($env{'form.f'.$i} ne 'none') {
 3815: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
 3816: 	    }
 3817: 	}
 3818:     }
 3819:     return %fields;
 3820: }
 3821: 
 3822: sub csvuploadassign {
 3823:     my ($request)= @_;
 3824:     my ($symb)=&get_symb($request);
 3825:     if (!$symb) {return '';}
 3826:     my $error_msg = '';
 3827:     &Apache::loncommon::load_tmp_file($request);
 3828:     my @gradedata = &Apache::loncommon::upfile_record_sep();
 3829:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
 3830:     my %fields=&get_fields();
 3831:     $request->print('<h3>Assigning Grades</h3>');
 3832:     my $courseid=$env{'request.course.id'};
 3833:     my ($classlist) = &getclasslist('all',0);
 3834:     my @notallowed;
 3835:     my @skipped;
 3836:     my $countdone=0;
 3837:     foreach my $grade (@gradedata) {
 3838: 	my %entries=&Apache::loncommon::record_sep($grade);
 3839: 	my $domain;
 3840: 	if ($entries{$fields{'domain'}}) {
 3841: 	    $domain=$entries{$fields{'domain'}};
 3842: 	} else {
 3843: 	    $domain=$env{'form.default_domain'};
 3844: 	}
 3845: 	$domain=~s/\s//g;
 3846: 	my $username=$entries{$fields{'username'}};
 3847: 	$username=~s/\s//g;
 3848: 	if (!$username) {
 3849: 	    my $id=$entries{$fields{'ID'}};
 3850: 	    $id=~s/\s//g;
 3851: 	    my %ids=&Apache::lonnet::idget($domain,$id);
 3852: 	    $username=$ids{$id};
 3853: 	}
 3854: 	if (!exists($$classlist{"$username:$domain"})) {
 3855: 	    my $id=$entries{$fields{'ID'}};
 3856: 	    $id=~s/\s//g;
 3857: 	    if ($id) {
 3858: 		push(@skipped,"$id:$domain");
 3859: 	    } else {
 3860: 		push(@skipped,"$username:$domain");
 3861: 	    }
 3862: 	    next;
 3863: 	}
 3864: 	my $usec=$classlist->{"$username:$domain"}[5];
 3865: 	if (!&canmodify($usec)) {
 3866: 	    push(@notallowed,"$username:$domain");
 3867: 	    next;
 3868: 	}
 3869: 	my %points;
 3870: 	my %grades;
 3871: 	foreach my $dest (keys(%fields)) {
 3872: 	    if ($dest eq 'ID' || $dest eq 'username' ||
 3873: 		$dest eq 'domain') { next; }
 3874: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
 3875: 	    if ($dest=~/stores_(.*)_points/) {
 3876: 		my $part=$1;
 3877: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
 3878: 					      $symb,$domain,$username);
 3879:                 if ($wgt) {
 3880:                     $entries{$fields{$dest}}=~s/\s//g;
 3881:                     my $pcr=$entries{$fields{$dest}} / $wgt;
 3882:                     my $award='correct_by_override';
 3883:                     $grades{"resource.$part.awarded"}=$pcr;
 3884:                     $grades{"resource.$part.solved"}=$award;
 3885:                     $points{$part}=1;
 3886:                 } else {
 3887:                     $error_msg = "<br />" .
 3888:                         &mt("Some point values were assigned"
 3889:                             ." for problems with a weight "
 3890:                             ."of zero. These values were "
 3891:                             ."ignored.");
 3892:                 }
 3893: 	    } else {
 3894: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
 3895: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
 3896: 		my $store_key=$dest;
 3897: 		$store_key=~s/^stores/resource/;
 3898: 		$store_key=~s/_/\./g;
 3899: 		$grades{$store_key}=$entries{$fields{$dest}};
 3900: 	    }
 3901: 	}
 3902: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
 3903: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 3904: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
 3905: 					   $env{'request.course.id'},
 3906: 					   $domain,$username);
 3907: 	if ($result eq 'ok') {
 3908: 	    $request->print('.');
 3909: 	} else {
 3910: 	    $request->print("<p>
 3911:                               <span class=\"LC_error\">
 3912:                                  Failed to save student $username:$domain.
 3913:                                  Message when trying to save was ($result)
 3914:                               </span>
 3915:                              </p>" );
 3916: 	}
 3917: 	$request->rflush();
 3918: 	$countdone++;
 3919:     }
 3920:     $request->print("<br />Saved $countdone students\n");
 3921:     if (@skipped) {
 3922: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
 3923: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
 3924:     }
 3925:     if (@notallowed) {
 3926: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
 3927: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
 3928:     }
 3929:     $request->print("<br />\n");
 3930:     $request->print(&show_grading_menu_form($symb));
 3931:     return $error_msg;
 3932: }
 3933: #------------- end of section for handling csv file upload ---------
 3934: #
 3935: #-------------------------------------------------------------------
 3936: #
 3937: #-------------- Next few routines handle grading by page/sequence
 3938: #
 3939: #--- Select a page/sequence and a student to grade
 3940: sub pickStudentPage {
 3941:     my ($request) = shift;
 3942: 
 3943:     $request->print(<<LISTJAVASCRIPT);
 3944: <script type="text/javascript" language="javascript">
 3945: 
 3946: function checkPickOne(formname) {
 3947:     if (radioSelection(formname.student) == null) {
 3948: 	alert("Please select the student you wish to grade.");
 3949: 	return;
 3950:     }
 3951:     ptr = pullDownSelection(formname.selectpage);
 3952:     formname.page.value = formname["page"+ptr].value;
 3953:     formname.title.value = formname["title"+ptr].value;
 3954:     formname.submit();
 3955: }
 3956: 
 3957: </script>
 3958: LISTJAVASCRIPT
 3959:     &commonJSfunctions($request);
 3960:     my ($symb) = &get_symb($request);
 3961:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 3962:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 3963:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 3964: 
 3965:     my $result='<h3><span class="LC_info">&nbsp;'.
 3966: 	'Manual Grading by Page or Sequence</span></h3>';
 3967: 
 3968:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
 3969:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
 3970:     my ($titles,$symbx) = &getSymbMap();
 3971:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
 3972: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
 3973: #    my $type=($curpage =~ /\.(page|sequence)/);
 3974:     my $ctr=0;
 3975:     foreach (@$titles) {
 3976: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 3977: 	$result.='<option value="'.$ctr.'" '.
 3978: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 3979: 	    '>'.$showtitle.'</option>'."\n";
 3980: 	$ctr++;
 3981:     }
 3982:     $result.= '</select>'."<br />\n";
 3983:     $ctr=0;
 3984:     foreach (@$titles) {
 3985: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 3986: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
 3987: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
 3988: 	$ctr++;
 3989:     }
 3990:     $result.='<input type="hidden" name="page" />'."\n".
 3991: 	'<input type="hidden" name="title" />'."\n";
 3992: 
 3993:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
 3994: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
 3995: 
 3996:     $result.='&nbsp;<b>Submission Details: </b>'.
 3997: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
 3998: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
 3999: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
 4000:     
 4001:     $result.=&build_section_inputs();
 4002:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
 4003:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
 4004: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 4005: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4006: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
 4007: 
 4008:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
 4009: 	'<input type="text" name="CODE" value="" /><br />'."\n";
 4010: 
 4011:     $result.='&nbsp;<input type="button" '.
 4012: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
 4013: 
 4014:     $request->print($result);
 4015: 
 4016:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
 4017: 	'<table border="0"><tr><td bgcolor="#777777">'.
 4018: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 4019: 	'<td align="right">&nbsp;<b>No.</b></td>'.
 4020: 	'<td>'.&nameUserString('header').'</td>'.
 4021: 	'<td align="right">&nbsp;<b>No.</b></td>'.
 4022: 	'<td>'.&nameUserString('header').'</td></tr>';
 4023:  
 4024:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
 4025:     my $ptr = 1;
 4026:     foreach my $student (sort 
 4027: 			 {
 4028: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
 4029: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
 4030: 			     }
 4031: 			     return $a cmp $b;
 4032: 			 } (keys(%$fullname))) {
 4033: 	my ($uname,$udom) = split(/:/,$student);
 4034: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
 4035: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
 4036: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
 4037: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
 4038: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
 4039: 	$ptr++;
 4040:     }
 4041:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
 4042:     $studentTable.='</table></td></tr></table>'."\n";
 4043:     $studentTable.='<input type="button" '.
 4044: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
 4045: 
 4046:     $studentTable.=&show_grading_menu_form($symb);
 4047:     $request->print($studentTable);
 4048: 
 4049:     return '';
 4050: }
 4051: 
 4052: sub getSymbMap {
 4053:     my $navmap = Apache::lonnavmaps::navmap->new();
 4054: 
 4055:     my %symbx = ();
 4056:     my @titles = ();
 4057:     my $minder = 0;
 4058: 
 4059:     # Gather every sequence that has problems.
 4060:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
 4061: 					       1,0,1);
 4062:     for my $sequence ($navmap->getById('0.0'), @sequences) {
 4063: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
 4064: 	    my $title = $minder.'.'.
 4065: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
 4066: 	    push(@titles, $title); # minder in case two titles are identical
 4067: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
 4068: 	    $minder++;
 4069: 	}
 4070:     }
 4071:     return \@titles,\%symbx;
 4072: }
 4073: 
 4074: #
 4075: #--- Displays a page/sequence w/wo problems, w/wo submissions
 4076: sub displayPage {
 4077:     my ($request) = shift;
 4078: 
 4079:     my ($symb) = &get_symb($request);
 4080:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4081:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4082:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4083:     my $pageTitle = $env{'form.page'};
 4084:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4085:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4086:     my $usec=$classlist->{$env{'form.student'}}[5];
 4087: 
 4088:     #need to make sure we have the correct data for later EXT calls, 
 4089:     #thus invalidate the cache
 4090:     &Apache::lonnet::devalidatecourseresdata(
 4091:                  $env{'course.'.$env{'request.course.id'}.'.num'},
 4092:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
 4093:     &Apache::lonnet::clear_EXT_cache_status();
 4094: 
 4095:     if (!&canview($usec)) {
 4096: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
 4097: 	$request->print(&show_grading_menu_form($symb));
 4098: 	return;
 4099:     }
 4100:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4101:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
 4102: 	'</h3>'."\n";
 4103:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4104: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
 4105:     } else {
 4106: 	delete($env{'form.CODE'});
 4107:     }
 4108:     &sub_page_js($request);
 4109:     $request->print($result);
 4110: 
 4111:     my $navmap = Apache::lonnavmaps::navmap->new();
 4112:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
 4113:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4114:     if (!$map) {
 4115: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
 4116: 	$request->print(&show_grading_menu_form($symb));
 4117: 	return; 
 4118:     }
 4119:     my $iterator = $navmap->getIterator($map->map_start(),
 4120: 					$map->map_finish());
 4121: 
 4122:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
 4123: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
 4124: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
 4125: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
 4126: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
 4127: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
 4128: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4129: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
 4130: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
 4131: 
 4132:     if (defined($env{'form.CODE'})) {
 4133: 	$studentTable.=
 4134: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
 4135:     }
 4136:     my $checkIcon = '<img alt="'.&mt('Check Mark').
 4137: 	'" src="'.$request->dir_config('lonIconsURL').
 4138: 	'/check.gif" height="16" border="0" />';
 4139: 
 4140:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
 4141: 	' symbol.'."\n".
 4142: 	'<table border="0"><tr><td bgcolor="#777777">'.
 4143: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 4144: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
 4145: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
 4146: 
 4147:     &Apache::lonxml::clear_problem_counter();
 4148:     my ($depth,$question,$prob) = (1,1,1);
 4149:     $iterator->next(); # skip the first BEGIN_MAP
 4150:     my $curRes = $iterator->next(); # for "current resource"
 4151:     while ($depth > 0) {
 4152:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4153:         if($curRes == $iterator->END_MAP) { $depth--; }
 4154: 
 4155:         if (ref($curRes) && $curRes->is_problem()) {
 4156: 	    my $parts = $curRes->parts();
 4157:             my $title = $curRes->compTitle();
 4158: 	    my $symbx = $curRes->symb();
 4159: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
 4160: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
 4161: 	    $studentTable.='<td valign="top">';
 4162: 	    my %form = ('CODE' => $env{'form.CODE'},);
 4163: 	    if ($env{'form.vProb'} eq 'yes' ) {
 4164: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
 4165: 					     undef,'both',\%form);
 4166: 	    } else {
 4167: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
 4168: 		$companswer =~ s|<form(.*?)>||g;
 4169: 		$companswer =~ s|</form>||g;
 4170: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 4171: #		    $companswer =~ s/$1/ /ms;
 4172: #		    $request->print('match='.$1."<br />\n");
 4173: #		}
 4174: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
 4175: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
 4176: 	    }
 4177: 
 4178: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
 4179: 
 4180: 	    if ($env{'form.lastSub'} eq 'datesub') {
 4181: 		if ($record{'version'} eq '') {
 4182: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
 4183: 		} else {
 4184: 		    my %responseType = ();
 4185: 		    foreach my $partid (@{$parts}) {
 4186: 			my @responseIds =$curRes->responseIds($partid);
 4187: 			my @responseType =$curRes->responseType($partid);
 4188: 			my %responseIds;
 4189: 			for (my $i=0;$i<=$#responseIds;$i++) {
 4190: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
 4191: 			}
 4192: 			$responseType{$partid} = \%responseIds;
 4193: 		    }
 4194: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
 4195: 
 4196: 		}
 4197: 	    } elsif ($env{'form.lastSub'} eq 'all') {
 4198: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
 4199: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
 4200: 									$env{'request.course.id'},
 4201: 									'','.submission');
 4202:  
 4203: 	    }
 4204: 	    if (&canmodify($usec)) {
 4205: 		foreach my $partid (@{$parts}) {
 4206: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
 4207: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
 4208: 		    $question++;
 4209: 		}
 4210: 		$prob++;
 4211: 	    }
 4212: 	    $studentTable.='</td></tr>';
 4213: 
 4214: 	}
 4215:         $curRes = $iterator->next();
 4216:     }
 4217: 
 4218:     $studentTable.='</table></td></tr></table>'."\n".
 4219: 	'<input type="button" value="Save" '.
 4220: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
 4221: 	'</form>'."\n";
 4222:     $studentTable.=&show_grading_menu_form($symb);
 4223:     $request->print($studentTable);
 4224: 
 4225:     return '';
 4226: }
 4227: 
 4228: sub displaySubByDates {
 4229:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
 4230:     my $isCODE=0;
 4231:     my $isTask = ($symb =~/\.task$/);
 4232:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
 4233:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
 4234: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
 4235: 	'<td><b>Date/Time</b></td>'.
 4236: 	($isCODE?'<td><b>CODE</b></td>':'').
 4237: 	'<td><b>Submission</b></td>'.
 4238: 	'<td><b>Status&nbsp;</b></td></tr>';
 4239:     my ($version);
 4240:     my %mark;
 4241:     my %orders;
 4242:     $mark{'correct_by_student'} = $checkIcon;
 4243:     if (!exists($$record{'1:timestamp'})) {
 4244: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
 4245:     }
 4246: 
 4247:     my $interaction;
 4248:     for ($version=1;$version<=$$record{'version'};$version++) {
 4249: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
 4250: 	if (exists($$record{$version.':resource.0.version'})) {
 4251: 	    $interaction = $$record{$version.':resource.0.version'};
 4252: 	}
 4253: 
 4254: 	my $where = ($isTask ? "$version:resource.$interaction"
 4255: 		             : "$version:resource");
 4256: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
 4257: 	if ($isCODE) {
 4258: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
 4259: 	}
 4260: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
 4261: 	my @displaySub = ();
 4262: 	foreach my $partid (@{$parts}) {
 4263: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
 4264: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
 4265: 	    
 4266: 
 4267: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
 4268: 	    my $display_part=&get_display_part($partid,$symb);
 4269: 	    foreach my $matchKey (@matchKey) {
 4270: 		if (exists($$record{$version.':'.$matchKey}) &&
 4271: 		    $$record{$version.':'.$matchKey} ne '') {
 4272: 
 4273: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
 4274: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
 4275: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
 4276: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
 4277: 			$responseId.')</span>&nbsp;<b>';
 4278: 		    if ($$record{"$where.$partid.tries"} eq '') {
 4279: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
 4280: 		    } else {
 4281: 			$displaySub[0].='Trial&nbsp;'.
 4282: 			    $$record{"$where.$partid.tries"};
 4283: 		    }
 4284: 		    my $responseType=($isTask ? 'Task'
 4285:                                               : $responseType->{$partid}->{$responseId});
 4286: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
 4287: 		    if (!exists($orders{$partid}->{$responseId})) {
 4288: 			$orders{$partid}->{$responseId}=
 4289: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
 4290: 		    }
 4291: 		    $displaySub[0].='</b>&nbsp; '.
 4292: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
 4293: 		}
 4294: 	    }
 4295: 	    if (exists($$record{"$where.$partid.checkedin"})) {
 4296: 		$displaySub[1].='Checked in by '.
 4297: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
 4298: 		    $$record{"$where.$partid.checkedin.slot"}.
 4299: 		    '<br />';
 4300: 	    }
 4301: 	    if (exists $$record{"$where.$partid.award"}) {
 4302: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
 4303: 		    lc($$record{"$where.$partid.award"}).' '.
 4304: 		    $mark{$$record{"$where.$partid.solved"}}.
 4305: 		    '<br />';
 4306: 	    }
 4307: 	    if (exists $$record{"$where.$partid.regrader"}) {
 4308: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
 4309: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4310: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
 4311: 		$displaySub[2].=
 4312: 		    $$record{"$version:resource.$partid.regrader"}.
 4313: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
 4314: 	    }
 4315: 	}
 4316: 	# needed because old essay regrader has not parts info
 4317: 	if (exists $$record{"$version:resource.regrader"}) {
 4318: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
 4319: 	}
 4320: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
 4321: 	if ($displaySub[2]) {
 4322: 	    $studentTable.='Manually graded by '.$displaySub[2];
 4323: 	}
 4324: 	$studentTable.='&nbsp;</td></tr>';
 4325:     
 4326:     }
 4327:     $studentTable.='</table></td></tr></table>';
 4328:     return $studentTable;
 4329: }
 4330: 
 4331: sub updateGradeByPage {
 4332:     my ($request) = shift;
 4333: 
 4334:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
 4335:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
 4336:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
 4337:     my $pageTitle = $env{'form.page'};
 4338:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
 4339:     my ($uname,$udom) = split(/:/,$env{'form.student'});
 4340:     my $usec=$classlist->{$env{'form.student'}}[5];
 4341:     if (!&canmodify($usec)) {
 4342: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
 4343: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
 4344: 	return;
 4345:     }
 4346:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
 4347:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
 4348: 	'</h3>'."\n";
 4349: 
 4350:     $request->print($result);
 4351: 
 4352:     my $navmap = Apache::lonnavmaps::navmap->new();
 4353:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
 4354:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
 4355:     if (!$map) {
 4356: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
 4357: 	my ($symb)=&get_symb($request);
 4358: 	$request->print(&show_grading_menu_form($symb));
 4359: 	return; 
 4360:     }
 4361:     my $iterator = $navmap->getIterator($map->map_start(),
 4362: 					$map->map_finish());
 4363: 
 4364:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
 4365: 	'<table border="0"><tr bgcolor="#e6ffff">'.
 4366: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
 4367: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
 4368: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
 4369: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
 4370: 
 4371:     $iterator->next(); # skip the first BEGIN_MAP
 4372:     my $curRes = $iterator->next(); # for "current resource"
 4373:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
 4374:     while ($depth > 0) {
 4375:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
 4376:         if($curRes == $iterator->END_MAP) { $depth--; }
 4377: 
 4378:         if (ref($curRes) && $curRes->is_problem()) {
 4379: 	    my $parts = $curRes->parts();
 4380:             my $title = $curRes->compTitle();
 4381: 	    my $symbx = $curRes->symb();
 4382: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
 4383: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
 4384: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
 4385: 
 4386: 	    my %newrecord=();
 4387: 	    my @displayPts=();
 4388:             my %aggregate = ();
 4389:             my $aggregateflag = 0;
 4390: 	    foreach my $partid (@{$parts}) {
 4391: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
 4392: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
 4393: 
 4394: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
 4395: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
 4396: 		my $partial = $newpts/$wgt;
 4397: 		my $score;
 4398: 		if ($partial > 0) {
 4399: 		    $score = 'correct_by_override';
 4400: 		} elsif ($newpts ne '') { #empty is taken as 0
 4401: 		    $score = 'incorrect_by_override';
 4402: 		}
 4403: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
 4404: 		if ($dropMenu eq 'excused') {
 4405: 		    $partial = '';
 4406: 		    $score = 'excused';
 4407: 		} elsif ($dropMenu eq 'reset status'
 4408: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
 4409: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
 4410: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
 4411: 		    $newrecord{'resource.'.$partid.'.award'} = '';
 4412: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
 4413: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
 4414: 		    $changeflag++;
 4415: 		    $newpts = '';
 4416:                     
 4417:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
 4418:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
 4419:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
 4420:                     if ($aggtries > 0) {
 4421:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
 4422:                         $aggregateflag = 1;
 4423:                     }
 4424: 		}
 4425: 		my $display_part=&get_display_part($partid,$curRes->symb());
 4426: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
 4427: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
 4428: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
 4429: 		    '&nbsp;<br />';
 4430: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
 4431: 		     (($score eq 'excused') ? 'excused' : $newpts).
 4432: 		    '&nbsp;<br />';
 4433: 		$question++;
 4434: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
 4435: 
 4436: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
 4437: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
 4438: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
 4439: 		    if (scalar(keys(%newrecord)) > 0);
 4440: 
 4441: 		$changeflag++;
 4442: 	    }
 4443: 	    if (scalar(keys(%newrecord)) > 0) {
 4444: 		my %record = 
 4445: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
 4446: 					     $udom,$uname);
 4447: 
 4448: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
 4449: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
 4450: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
 4451: 		    $newrecord{'resource.CODE'} = '';
 4452: 		}
 4453: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
 4454: 					$udom,$uname);
 4455: 		%record = &Apache::lonnet::restore($symbx,
 4456: 						   $env{'request.course.id'},
 4457: 						   $udom,$uname);
 4458: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
 4459: 					     $cdom,$cnum,$udom,$uname);
 4460: 	    }
 4461: 	    
 4462:             if ($aggregateflag) {
 4463:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
 4464:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
 4465:                       $env{'course.'.$env{'request.course.id'}.'.num'});
 4466:             }
 4467: 
 4468: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
 4469: 		'<td valign="top">'.$displayPts[1].'</td>'.
 4470: 		'</tr>';
 4471: 
 4472: 	    $prob++;
 4473: 	}
 4474:         $curRes = $iterator->next();
 4475:     }
 4476: 
 4477:     $studentTable.='</td></tr></table></td></tr></table>';
 4478:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
 4479:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
 4480: 		  'The scores were changed for '.
 4481: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
 4482:     $request->print($grademsg.$studentTable);
 4483: 
 4484:     return '';
 4485: }
 4486: 
 4487: #-------- end of section for handling grading by page/sequence ---------
 4488: #
 4489: #-------------------------------------------------------------------
 4490: 
 4491: #--------------------Scantron Grading-----------------------------------
 4492: #
 4493: #------ start of section for handling grading by page/sequence ---------
 4494: 
 4495: =pod
 4496: 
 4497: =head1 Bubble sheet grading routines
 4498: 
 4499:   For this documentation:
 4500: 
 4501:    'scanline' refers to the full line of characters
 4502:    from the file that we are parsing that represents one entire sheet
 4503: 
 4504:    'bubble line' refers to the data
 4505:    representing the line of bubbles that are on the physical bubble sheet
 4506: 
 4507: 
 4508: The overall process is that a scanned in bubble sheet data is uploaded
 4509: into a course. When a user wants to grade, they select a
 4510: sequence/folder of resources, a file of bubble sheet info, and pick
 4511: one of the predefined configurations for what each scanline looks
 4512: like.
 4513: 
 4514: Next each scanline is checked for any errors of either 'missing
 4515: bubbles' (it's an error because it may have been mis-scanned
 4516: because too light bubbling), 'double bubble' (each bubble line should
 4517: have no more that one letter picked), invalid or duplicated CODE,
 4518: invalid student ID
 4519: 
 4520: If the CODE option is used that determines the randomization of the
 4521: homework problems, either way the student ID is looked up into a
 4522: username:domain.
 4523: 
 4524: During the validation phase the instructor can choose to skip scanlines. 
 4525: 
 4526: After the validation phase, there are now 3 bubble sheet files
 4527: 
 4528:   scantron_original_filename (unmodified original file)
 4529:   scantron_corrected_filename (file where the corrected information has replaced the original information)
 4530:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
 4531: 
 4532: Also there is a separate hash nohist_scantrondata that contains extra
 4533: correction information that isn't representable in the bubble sheet
 4534: file (see &scantron_getfile() for more information)
 4535: 
 4536: After all scanlines are either valid, marked as valid or skipped, then
 4537: foreach line foreach problem in the picked sequence, an ssi request is
 4538: made that simulates a user submitting their selected letter(s) against
 4539: the homework problem.
 4540: 
 4541: =over 4
 4542: 
 4543: 
 4544: 
 4545: =item defaultFormData
 4546: 
 4547:   Returns html hidden inputs used to hold context/default values.
 4548: 
 4549:  Arguments:
 4550:   $symb - $symb of the current resource 
 4551: 
 4552: =cut
 4553: 
 4554: sub defaultFormData {
 4555:     my ($symb)=@_;
 4556:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 4557:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
 4558:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
 4559: }
 4560: 
 4561: 
 4562: =pod 
 4563: 
 4564: =item getSequenceDropDown
 4565: 
 4566:    Return html dropdown of possible sequences to grade
 4567:  
 4568:  Arguments:
 4569:    $symb - $symb of the current resource 
 4570: 
 4571: =cut
 4572: 
 4573: sub getSequenceDropDown {
 4574:     my ($symb)=@_;
 4575:     my $result='<select name="selectpage">'."\n";
 4576:     my ($titles,$symbx) = &getSymbMap();
 4577:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
 4578:     my $ctr=0;
 4579:     foreach (@$titles) {
 4580: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
 4581: 	$result.='<option value="'.$$symbx{$_}.'" '.
 4582: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
 4583: 	    '>'.$showtitle.'</option>'."\n";
 4584: 	$ctr++;
 4585:     }
 4586:     $result.= '</select>';
 4587:     return $result;
 4588: }
 4589: 
 4590: 
 4591: =pod 
 4592: 
 4593: =item scantron_filenames
 4594: 
 4595:    Returns a list of the scantron files in the current course 
 4596: 
 4597: =cut
 4598: 
 4599: sub scantron_filenames {
 4600:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4601:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4602:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
 4603: 				    &propath($cdom,$cname));
 4604:     my @possiblenames;
 4605:     foreach my $filename (sort(@files)) {
 4606: 	($filename)=split(/&/,$filename);
 4607: 	if ($filename!~/^scantron_orig_/) { next ; }
 4608: 	$filename=~s/^scantron_orig_//;
 4609: 	push(@possiblenames,$filename);
 4610:     }
 4611:     return @possiblenames;
 4612: }
 4613: 
 4614: =pod 
 4615: 
 4616: =item scantron_uploads
 4617: 
 4618:    Returns  html drop-down list of scantron files in current course.
 4619: 
 4620:  Arguments:
 4621:    $file2grade - filename to set as selected in the dropdown
 4622: 
 4623: =cut
 4624: 
 4625: sub scantron_uploads {
 4626:     my ($file2grade) = @_;
 4627:     my $result=	'<select name="scantron_selectfile">';
 4628:     $result.="<option></option>";
 4629:     foreach my $filename (sort(&scantron_filenames())) {
 4630: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
 4631:     }
 4632:     $result.="</select>";
 4633:     return $result;
 4634: }
 4635: 
 4636: =pod 
 4637: 
 4638: =item scantron_scantab
 4639: 
 4640:   Returns html drop down of the scantron formats in the scantronformat.tab
 4641:   file.
 4642: 
 4643: =cut
 4644: 
 4645: sub scantron_scantab {
 4646:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4647:     my $result='<select name="scantron_format">'."\n";
 4648:     $result.='<option></option>'."\n";
 4649:     foreach my $line (<$fh>) {
 4650: 	my ($name,$descrip)=split(/:/,$line);
 4651: 	if ($name =~ /^\#/) { next; }
 4652: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
 4653:     }
 4654:     $result.='</select>'."\n";
 4655: 
 4656:     return $result;
 4657: }
 4658: 
 4659: =pod 
 4660: 
 4661: =item scantron_CODElist
 4662: 
 4663:   Returns html drop down of the saved CODE lists from current course,
 4664:   generated from earlier printings.
 4665: 
 4666: =cut
 4667: 
 4668: sub scantron_CODElist {
 4669:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4670:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4671:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
 4672:     my $namechoice='<option></option>';
 4673:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
 4674: 	if ($name =~ /^error: 2 /) { next; }
 4675: 	if ($name =~ /^type\0/) { next; }
 4676: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
 4677:     }
 4678:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
 4679:     return $namechoice;
 4680: }
 4681: 
 4682: =pod 
 4683: 
 4684: =item scantron_CODEunique
 4685: 
 4686:   Returns the html for "Each CODE to be used once" radio.
 4687: 
 4688: =cut
 4689: 
 4690: sub scantron_CODEunique {
 4691:     my $result='<span style="white-space: nowrap;">
 4692:                  <label><input type="radio" name="scantron_CODEunique"
 4693:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
 4694:                 </span>
 4695:                 <span style="white-space: nowrap;">
 4696:                  <label><input type="radio" name="scantron_CODEunique"
 4697:                         value="no" />'.&mt('No').' </label>
 4698:                 </span>';
 4699:     return $result;
 4700: }
 4701: 
 4702: =pod 
 4703: 
 4704: =item scantron_selectphase
 4705: 
 4706:   Generates the initial screen to start the bubble sheet process.
 4707:   Allows for - starting a grading run.
 4708:              - downloading existing scan data (original, corrected
 4709:                                                 or skipped info)
 4710: 
 4711:              - uploading new scan data
 4712: 
 4713:  Arguments:
 4714:   $r          - The Apache request object
 4715:   $file2grade - name of the file that contain the scanned data to score
 4716: 
 4717: =cut
 4718: 
 4719: sub scantron_selectphase {
 4720:     my ($r,$file2grade) = @_;
 4721:     my ($symb)=&get_symb($r);
 4722:     if (!$symb) {return '';}
 4723:     my $sequence_selector=&getSequenceDropDown($symb);
 4724:     my $default_form_data=&defaultFormData($symb);
 4725:     my $grading_menu_button=&show_grading_menu_form($symb);
 4726:     my $file_selector=&scantron_uploads($file2grade);
 4727:     my $format_selector=&scantron_scantab();
 4728:     my $CODE_selector=&scantron_CODElist();
 4729:     my $CODE_unique=&scantron_CODEunique();
 4730:     my $result;
 4731: 
 4732:     # Chunk of form to prompt for a file to grade and how:
 4733: 
 4734:     $result.= <<SCANTRONFORM;
 4735:     <table width="100%" border="0">
 4736:     <tr>
 4737:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
 4738:       <td bgcolor="#777777">
 4739:        <input type="hidden" name="command" value="scantron_warning" />
 4740:         $default_form_data
 4741:         <table width="100%" border="0">
 4742:           <tr bgcolor="#e6ffff">
 4743:             <td colspan="2">
 4744:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
 4745:             </td>
 4746:           </tr>
 4747:           <tr bgcolor="#ffffe6">
 4748:             <td> Sequence to grade: </td><td> $sequence_selector </td>
 4749:           </tr>
 4750:           <tr bgcolor="#ffffe6">
 4751:             <td> Filename of scoring office file: </td><td> $file_selector </td>
 4752:           </tr>
 4753:           <tr bgcolor="#ffffe6">
 4754:             <td> Format of data file: </td><td> $format_selector </td>
 4755:           </tr>
 4756:           <tr bgcolor="#ffffe6">
 4757:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
 4758:           </tr>
 4759:           <tr bgcolor="#ffffe6">
 4760:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
 4761:           </tr>
 4762:           <tr bgcolor="#ffffe6">
 4763: 	    <td> Options: </td>
 4764:             <td>
 4765: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
 4766:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
 4767:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
 4768: 	    </td>
 4769:           </tr>
 4770:           <tr bgcolor="#ffffe6">
 4771:             <td colspan="2">
 4772:               <input type="submit" value="Grading: Validate Scantron Records" />
 4773:             </td>
 4774:           </tr>
 4775:         </table>
 4776:        </td>
 4777:      </form>
 4778:     </tr>
 4779: SCANTRONFORM
 4780:    
 4781:     $r->print($result);
 4782: 
 4783:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
 4784:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 4785: 
 4786: 	# Chunk of form to prompt for a scantron file upload.
 4787: 
 4788:         $r->print(<<SCANTRONFORM);
 4789:     <tr>
 4790:       <td bgcolor="#777777">
 4791:         <table width="100%" border="0">
 4792:           <tr bgcolor="#e6ffff">
 4793:             <td>
 4794:               &nbsp;<b>Specify a Scantron data file to upload.</b>
 4795:             </td>
 4796:           </tr>
 4797:           <tr bgcolor="#ffffe6">
 4798:             <td>
 4799: SCANTRONFORM
 4800:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 4801:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4802:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
 4803:     $r->print(<<UPLOAD);
 4804:               <script type="text/javascript" language="javascript">
 4805:     function checkUpload(formname) {
 4806: 	if (formname.upfile.value == "") {
 4807: 	    alert("Please use the browse button to select a file from your local directory.");
 4808: 	    return false;
 4809: 	}
 4810: 	formname.submit();
 4811:     }
 4812:               </script>
 4813: 
 4814:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
 4815:                 $default_form_data
 4816:                 <input name='courseid' type='hidden' value='$cnum' />
 4817:                 <input name='domainid' type='hidden' value='$cdom' />
 4818:                 <input name='command' value='scantronupload_save' type='hidden' />
 4819:                 File to upload:<input type="file" name="upfile" size="50" />
 4820:                 <br />
 4821:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
 4822:               </form>
 4823: UPLOAD
 4824: 
 4825:         $r->print(<<SCANTRONFORM);
 4826:             </td>
 4827:           </tr>
 4828:         </table>
 4829:       </td>
 4830:     </tr>
 4831: SCANTRONFORM
 4832:     }
 4833: 
 4834:     # Chunk of the form that prompts to view a scoring office file,
 4835:     # corrected file, skipped records in a file.
 4836: 
 4837:     $r->print(<<SCANTRONFORM);
 4838:     <tr>
 4839:       <form action='/adm/grades' name='scantron_download'>
 4840:         <td bgcolor="#777777">
 4841: 	  $default_form_data
 4842:           <input type="hidden" name="command" value="scantron_download" />
 4843:           <table width="100%" border="0">
 4844:             <tr bgcolor="#e6ffff">
 4845:               <td colspan="2">
 4846:                 &nbsp;<b>Download a scoring office file</b>
 4847:               </td>
 4848:             </tr>
 4849:             <tr bgcolor="#ffffe6">
 4850:               <td> Filename of scoring office file: </td><td> $file_selector </td>
 4851:             </tr>
 4852:             <tr bgcolor="#ffffe6">
 4853:               <td colspan="2">
 4854:                 <input type="submit" value="Download: Show List of Associated Files" />
 4855:               </td>
 4856:             </tr>
 4857:           </table>
 4858:         </td>
 4859:       </form>
 4860:     </tr>
 4861: SCANTRONFORM
 4862: 
 4863:     $r->print(<<SCANTRONFORM);
 4864:   </table>
 4865: $grading_menu_button
 4866: SCANTRONFORM
 4867: 
 4868:     return
 4869: }
 4870: 
 4871: =pod
 4872: 
 4873: =item get_scantron_config
 4874: 
 4875:    Parse and return the scantron configuration line selected as a
 4876:    hash of configuration file fields.
 4877: 
 4878:  Arguments:
 4879:     which - the name of the configuration to parse from the file.
 4880: 
 4881: 
 4882:  Returns:
 4883:             If the named configuration is not in the file, an empty
 4884:             hash is returned.
 4885:     a hash with the fields
 4886:       name         - internal name for the this configuration setup
 4887:       description  - text to display to operator that describes this config
 4888:       CODElocation - if 0 or the string 'none'
 4889:                           - no CODE exists for this config
 4890:                      if -1 || the string 'letter'
 4891:                           - a CODE exists for this config and is
 4892:                             a string of letters
 4893:                      Unsupported value (but planned for future support)
 4894:                           if a positive integer
 4895:                                - The CODE exists as the first n items from
 4896:                                  the question section of the form
 4897:                           if the string 'number'
 4898:                                - The CODE exists for this config and is
 4899:                                  a string of numbers
 4900:       CODEstart   - (only matter if a CODE exists) column in the line where
 4901:                      the CODE starts
 4902:       CODElength  - length of the CODE
 4903:       IDstart     - column where the student ID number starts
 4904:       IDlength    - length of the student ID info
 4905:       Qstart      - column where the information from the bubbled
 4906:                     'questions' start
 4907:       Qlength     - number of columns comprising a single bubble line from
 4908:                     the sheet. (usually either 1 or 10)
 4909:       Qon         - either a single character representing the character used
 4910:                     to signal a bubble was chosen in the positional setup, or
 4911:                     the string 'letter' if the letter of the chosen bubble is
 4912:                     in the final, or 'number' if a number representing the
 4913:                     chosen bubble is in the file (1->A 0->J)
 4914:       Qoff        - the character used to represent that a bubble was
 4915:                     left blank
 4916:       PaperID     - if the scanning process generates a unique number for each
 4917:                     sheet scanned the column that this ID number starts in
 4918:       PaperIDlength - number of columns that comprise the unique ID number
 4919:                       for the sheet of paper
 4920:       FirstName   - column that the first name starts in
 4921:       FirstNameLength - number of columns that the first name spans
 4922:  
 4923:       LastName    - column that the last name starts in
 4924:       LastNameLength - number of columns that the last name spans
 4925: 
 4926: =cut
 4927: 
 4928: sub get_scantron_config {
 4929:     my ($which) = @_;
 4930:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
 4931:     my %config;
 4932:     #FIXME probably should move to XML it has already gotten a bit much now
 4933:     foreach my $line (<$fh>) {
 4934: 	my ($name,$descrip)=split(/:/,$line);
 4935: 	if ($name ne $which ) { next; }
 4936: 	chomp($line);
 4937: 	my @config=split(/:/,$line);
 4938: 	$config{'name'}=$config[0];
 4939: 	$config{'description'}=$config[1];
 4940: 	$config{'CODElocation'}=$config[2];
 4941: 	$config{'CODEstart'}=$config[3];
 4942: 	$config{'CODElength'}=$config[4];
 4943: 	$config{'IDstart'}=$config[5];
 4944: 	$config{'IDlength'}=$config[6];
 4945: 	$config{'Qstart'}=$config[7];
 4946: 	$config{'Qlength'}=$config[8];
 4947: 	$config{'Qoff'}=$config[9];
 4948: 	$config{'Qon'}=$config[10];
 4949: 	$config{'PaperID'}=$config[11];
 4950: 	$config{'PaperIDlength'}=$config[12];
 4951: 	$config{'FirstName'}=$config[13];
 4952: 	$config{'FirstNamelength'}=$config[14];
 4953: 	$config{'LastName'}=$config[15];
 4954: 	$config{'LastNamelength'}=$config[16];
 4955: 	last;
 4956:     }
 4957:     return %config;
 4958: }
 4959: 
 4960: =pod 
 4961: 
 4962: =item username_to_idmap
 4963: 
 4964:     creates a hash keyed by student id with values of the corresponding
 4965:     student username:domain.
 4966: 
 4967:   Arguments:
 4968: 
 4969:     $classlist - reference to the class list hash. This is a hash
 4970:                  keyed by student name:domain  whose elements are references
 4971:                  to arrays containing various chunks of information
 4972:                  about the student. (See loncoursedata for more info).
 4973: 
 4974:   Returns
 4975:     %idmap - the constructed hash
 4976: 
 4977: =cut
 4978: 
 4979: sub username_to_idmap {
 4980:     my ($classlist)= @_;
 4981:     my %idmap;
 4982:     foreach my $student (keys(%$classlist)) {
 4983: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
 4984: 	    $student;
 4985:     }
 4986:     return %idmap;
 4987: }
 4988: 
 4989: =pod
 4990: 
 4991: =item scantron_fixup_scanline
 4992: 
 4993:    Process a requested correction to a scanline.
 4994: 
 4995:   Arguments:
 4996:     $scantron_config   - hash from &get_scantron_config()
 4997:     $scan_data         - hash of correction information 
 4998:                           (see &scantron_getfile())
 4999:     $line              - existing scanline
 5000:     $whichline         - line number of the passed in scanline
 5001:     $field             - type of change to process 
 5002:                          (either 
 5003:                           'ID'     -> correct the student ID number
 5004:                           'CODE'   -> correct the CODE
 5005:                           'answer' -> fixup the submitted answers)
 5006:     
 5007:    $args               - hash of additional info,
 5008:                           - 'ID' 
 5009:                                'newid' -> studentID to use in replacement
 5010:                                           of existing one
 5011:                           - 'CODE' 
 5012:                                'CODE_ignore_dup' - set to true if duplicates
 5013:                                                    should be ignored.
 5014: 	                       'CODE' - is new code or 'use_unfound'
 5015:                                         if the existing unfound code should
 5016:                                         be used as is
 5017:                           - 'answer'
 5018:                                'response' - new answer or 'none' if blank
 5019:                                'question' - the bubble line to change
 5020: 
 5021:   Returns:
 5022:     $line - the modified scanline
 5023: 
 5024:   Side effects: 
 5025:     $scan_data - may be updated
 5026: 
 5027: =cut
 5028: 
 5029: 
 5030: sub scantron_fixup_scanline {
 5031:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
 5032: 
 5033:     if ($field eq 'ID') {
 5034: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
 5035: 	    return ($line,1,'New value too large');
 5036: 	}
 5037: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
 5038: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
 5039: 				     $args->{'newid'});
 5040: 	}
 5041: 	substr($line,$$scantron_config{'IDstart'}-1,
 5042: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
 5043: 	if ($args->{'newid'}=~/^\s*$/) {
 5044: 	    &scan_data($scan_data,"$whichline.user",
 5045: 		       $args->{'username'}.':'.$args->{'domain'});
 5046: 	}
 5047:     } elsif ($field eq 'CODE') {
 5048: 	if ($args->{'CODE_ignore_dup'}) {
 5049: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
 5050: 	}
 5051: 	&scan_data($scan_data,"$whichline.useCODE",'1');
 5052: 	if ($args->{'CODE'} ne 'use_unfound') {
 5053: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
 5054: 		return ($line,1,'New CODE value too large');
 5055: 	    }
 5056: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
 5057: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
 5058: 	    }
 5059: 	    substr($line,$$scantron_config{'CODEstart'}-1,
 5060: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
 5061: 	}
 5062:     } elsif ($field eq 'answer') {
 5063: 	my $length=$scantron_config->{'Qlength'};
 5064: 	my $off=$scantron_config->{'Qoff'};
 5065: 	my $on=$scantron_config->{'Qon'};
 5066: 	my $answer=${off}x$length;
 5067: 	if ($args->{'response'} eq 'none') {
 5068: 	    &scan_data($scan_data,
 5069: 		       "$whichline.no_bubble.".$args->{'question'},'1');
 5070: 	} else {
 5071: 	    if ($on eq 'letter') {
 5072: 		my @alphabet=('A'..'Z');
 5073: 		$answer=$alphabet[$args->{'response'}];
 5074: 	    } elsif ($on eq 'number') {
 5075: 		$answer=$args->{'response'}+1;
 5076: 		if ($answer == 10) { $answer = '0'; }
 5077: 	    } else {
 5078: 		substr($answer,$args->{'response'},1)=$on;
 5079: 	    }
 5080: 	    &scan_data($scan_data,
 5081: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
 5082: 	}
 5083: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
 5084: 	substr($line,$where-1,$length)=$answer;
 5085:     }
 5086:     return $line;
 5087: }
 5088: 
 5089: =pod
 5090: 
 5091: =item scan_data
 5092: 
 5093:     Edit or look up  an item in the scan_data hash.
 5094: 
 5095:   Arguments:
 5096:     $scan_data  - The hash (see scantron_getfile)
 5097:     $key        - shorthand of the key to edit (actual key is
 5098:                   scantronfilename_key).
 5099:     $data        - New value of the hash entry.
 5100:     $delete      - If true, the entry is removed from the hash.
 5101: 
 5102:   Returns:
 5103:     The new value of the hash table field (undefined if deleted).
 5104: 
 5105: =cut
 5106: 
 5107: 
 5108: sub scan_data {
 5109:     my ($scan_data,$key,$value,$delete)=@_;
 5110:     my $filename=$env{'form.scantron_selectfile'};
 5111:     if (defined($value)) {
 5112: 	$scan_data->{$filename.'_'.$key} = $value;
 5113:     }
 5114:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
 5115:     return $scan_data->{$filename.'_'.$key};
 5116: }
 5117: 
 5118: =pod 
 5119: 
 5120: =item scantron_parse_scanline
 5121: 
 5122:   Decodes a scanline from the selected scantron file
 5123: 
 5124:  Arguments:
 5125:     line             - The text of the scantron file line to process
 5126:     whichline        - Line number
 5127:     scantron_config  - Hash describing the format of the scantron lines.
 5128:     scan_data        - Hash of extra information about the scanline
 5129:                        (see scantron_getfile for more information)
 5130:     just_header      - True if should not process question answers but only
 5131:                        the stuff to the left of the answers.
 5132:  Returns:
 5133:    Hash containing the result of parsing the scanline
 5134: 
 5135:    Keys are all proceeded by the string 'scantron.'
 5136: 
 5137:        CODE    - the CODE in use for this scanline
 5138:        useCODE - 1 if the CODE is invalid but it usage has been forced
 5139:                  by the operator
 5140:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
 5141:                             CODEs were selected, but the usage has been
 5142:                             forced by the operator
 5143:        ID  - student ID
 5144:        PaperID - if used, the ID number printed on the sheet when the 
 5145:                  paper was scanned
 5146:        FirstName - first name from the sheet
 5147:        LastName  - last name from the sheet
 5148: 
 5149:      if just_header was not true these key may also exist
 5150: 
 5151:        missingerror - a list of bubble ranges that are considered to be answers
 5152:                       to a single question that don't have any bubbles filled in.
 5153:                       Of the form questionnumber:firstbubblenumber:count.
 5154:        doubleerror  - a list of bubble ranges that are considered to be answers
 5155:                       to a single question that have more than one bubble filled in.
 5156:                       Of the form questionnumber::firstbubblenumber:count
 5157:    
 5158:                 In the above, count is the number of bubble responses in the
 5159:                 input line needed to represent the possible answers to the question.
 5160:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
 5161:                 per line would have count = 2.
 5162: 
 5163:        maxquest     - the number of the last bubble line that was parsed
 5164: 
 5165:        (<number> starts at 1)
 5166:        <number>.answer - zero or more letters representing the selected
 5167:                          letters from the scanline for the bubble line 
 5168:                          <number>.
 5169:                          if blank there was either no bubble or there where
 5170:                          multiple bubbles, (consult the keys missingerror and
 5171:                          doubleerror if this is an error condition)
 5172: 
 5173: =cut
 5174: 
 5175: sub scantron_parse_scanline {
 5176:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
 5177:     my %record;
 5178:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
 5179:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
 5180:     if (!($$scantron_config{'CODElocation'} eq 0 ||
 5181: 	  $$scantron_config{'CODElocation'} eq 'none')) {
 5182: 	if ($$scantron_config{'CODElocation'} < 0 ||
 5183: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
 5184: 	    $$scantron_config{'CODElocation'} eq 'number') {
 5185: 	    $record{'scantron.CODE'}=substr($data,
 5186: 					    $$scantron_config{'CODEstart'}-1,
 5187: 					    $$scantron_config{'CODElength'});
 5188: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
 5189: 		$record{'scantron.useCODE'}=1;
 5190: 	    }
 5191: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
 5192: 		$record{'scantron.CODE_ignore_dup'}=1;
 5193: 	    }
 5194: 	} else {
 5195: 	    #FIXME interpret first N questions
 5196: 	}
 5197:     }
 5198:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
 5199: 				  $$scantron_config{'IDlength'});
 5200:     $record{'scantron.PaperID'}=
 5201: 	substr($data,$$scantron_config{'PaperID'}-1,
 5202: 	       $$scantron_config{'PaperIDlength'});
 5203:     $record{'scantron.FirstName'}=
 5204: 	substr($data,$$scantron_config{'FirstName'}-1,
 5205: 	       $$scantron_config{'FirstNamelength'});
 5206:     $record{'scantron.LastName'}=
 5207: 	substr($data,$$scantron_config{'LastName'}-1,
 5208: 	       $$scantron_config{'LastNamelength'});
 5209:     if ($just_header) { return \%record; }
 5210: 
 5211:     my @alphabet=('A'..'Z');
 5212:     my $questnum=0;
 5213:     my $ansnum  =1;		# Multiple 'answer lines'/question.
 5214: 
 5215:     while ($questions) {
 5216: 	my $answers_needed = $bubble_lines_per_response{$questnum};
 5217: 	my $answer_length  = $$scantron_config{'Qlength'} * $answers_needed;
 5218: 
 5219: 
 5220: 
 5221: 	$questnum++;
 5222: 	my $currentquest = substr($questions,0,$answer_length);
 5223: 	$questions       = substr($questions,0,$answer_length)='';
 5224: 	if (length($currentquest) < $answer_length) { next; }
 5225: 
 5226: 	# Qon letter implies for each slot in currentquest we have:
 5227: 	#    ? or * for doubles a letter in A-Z for a bubble and
 5228:         #    about anything else (esp. a value of Qoff for missing
 5229: 	#    bubbles.
 5230: 
 5231: 
 5232: 	if ($$scantron_config{'Qon'} eq 'letter') {
 5233: 
 5234: 	    if ($currentquest =~ /\?/
 5235: 		|| $currentquest =~ /\*/
 5236: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
 5237: 		push(@{$record{'scantron.doubleerror'}},$questnum);
 5238: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
 5239: 		    $record{"scantron.$ansnum.answer"}='';
 5240: 		    $ansnum++;
 5241: 		}
 5242: 
 5243: 	    } elsif (!defined($currentquest)
 5244: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
 5245: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
 5246: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
 5247: 		    $record{"scantron.$ansnum.answer"}='';
 5248: 		    $ansnum++;
 5249: 
 5250: 		}
 5251: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
 5252: 		    push(@{$record{"scantron.missingerror"}},$questnum);
 5253: 		    $ansnum += $answers_needed;
 5254: 		}
 5255: 
 5256: 	    } else {
 5257: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
 5258: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
 5259: 		    $ansnum++;
 5260: 		}
 5261: 	    }
 5262: 
 5263: 	# Qon 'number' implies each slot gives a digit that indexes the
 5264: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
 5265:         #    and *? for double bubbles on a line.
 5266: 	#    these answers are also stored as letters.
 5267: 
 5268: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
 5269: 	    if ($currentquest =~ /\?/
 5270: 		|| $currentquest =~ /\*/
 5271: 		|| (&occurence_count($currentquest, '\d') > 1)) {
 5272: 		push(@{$record{'scantron.doubleerror'}},$questnum);
 5273: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
 5274: 		    $record{"scantron.$ansnum.answer"}='';
 5275: 		    $ansnum++;
 5276: 		}
 5277: 
 5278: 	    } elsif (!defined($currentquest)
 5279: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
 5280: 		     || (&occurence_count($currentquest, '\d') == 0)) {
 5281: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
 5282: 		    $record{"scantron.$ansnum.answer"}='';
 5283: 		    $ansnum++;
 5284: 
 5285: 		}
 5286: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
 5287: 		    push(@{$record{"scantron.missingerror"}},$questnum);
 5288: 		    $ansnum += $answers_needed;
 5289: 		}
 5290: 
 5291: 	    } else {
 5292: 		$currentquest = &digits_to_letters($currentquest);
 5293: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
 5294: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
 5295: 		    $ansnum++;
 5296: 		}
 5297: 	    }
 5298: 	} else {
 5299: 
 5300: 	    # Otherwise there's a positional notation;
 5301: 	    # each bubble line requires Qlength items, and there are filled in
 5302: 	    # bubbles for each case where there 'Qon' characters.
 5303: 	    #
 5304: 
 5305: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
 5306: 
 5307: 	    # If the split only  giveas us one element.. the full length of the
 5308: 	    # answser string, no bubbles are filled in:
 5309: 
 5310: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
 5311: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
 5312: 		    $record{"scantron.$ansnum.answer"}='';
 5313: 		    $ansnum++;
 5314: 
 5315: 		}
 5316: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
 5317: 		    push(@{$record{"scantron.missingerror"}},$questnum);
 5318: 		}
 5319: 	    } elsif (scalar(@array) lt 2) {
 5320: 
 5321: 		my $location      = [length($array[0])];
 5322: 		my $line_num      = $location / $$scantron_config{'Qlength'};
 5323: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
 5324: 
 5325: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
 5326: 		    if ($ans eq $line_num) {
 5327: 			$record{"scantron.$ansnum.answer"} = $bubble;
 5328: 		    } else {
 5329: 			$record{"scantron.$ansnum.answer"} = ' ';
 5330: 		    }
 5331: 		    $ansnum++;
 5332: 		}
 5333: 	    }
 5334: 	    #  If there's more than one instance of a bubble character
 5335: 	    #  That's a double bubble; with positional notation we can
 5336: 	    #  record all the bubbles filled in as well as the 
 5337: 	    #  fact this response consists of multiple bubbles.
 5338: 	    #
 5339: 	    else {
 5340: 		push(@{$record{'scantron.doubleerror'}},$questnum);
 5341: 
 5342: 		my $first_answer = $ansnum;
 5343: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
 5344: 		    $record{"scantron.$ansnum.answer"} = '';
 5345: 		    $ans++;
 5346: 		}
 5347: 
 5348: 		my @ans=@array;
 5349: 		my $i=length($ans[0]);shift(@ans);
 5350: 		while ($#ans) {
 5351: 		    $i+=length($ans[0])+1;
 5352: 		    my $line   = $i/$$scantron_config{'Qlength'} + $first_answer;
 5353: 		    my $bubble = $i%$$scantron_config{'Qlength'};
 5354: 
 5355: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
 5356: 		    shift(@ans);
 5357: 		}
 5358: 	    }
 5359: 	}
 5360:     }
 5361:     $record{'scantron.maxquest'}=$questnum;
 5362:     return \%record;
 5363: }
 5364: 
 5365: =pod
 5366: 
 5367: =item scantron_add_delay
 5368: 
 5369:    Adds an error message that occurred during the grading phase to a
 5370:    queue of messages to be shown after grading pass is complete
 5371: 
 5372:  Arguments:
 5373:    $delayqueue  - arrary ref of hash ref of error messages
 5374:    $scanline    - the scanline that caused the error
 5375:    $errormesage - the error message
 5376:    $errorcode   - a numeric code for the error
 5377: 
 5378:  Side Effects:
 5379:    updates the $delayqueue to have a new hash ref of the error
 5380: 
 5381: =cut
 5382: 
 5383: sub scantron_add_delay {
 5384:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
 5385:     push(@$delayqueue,
 5386: 	 {'line' => $scanline, 'emsg' => $errormessage,
 5387: 	  'ecode' => $errorcode }
 5388: 	 );
 5389: }
 5390: 
 5391: =pod
 5392: 
 5393: =item scantron_find_student
 5394: 
 5395:    Finds the username for the current scanline
 5396: 
 5397:   Arguments:
 5398:    $scantron_record - hash result from scantron_parse_scanline
 5399:    $scan_data       - hash of correction information 
 5400:                       (see &scantron_getfile() form more information)
 5401:    $idmap           - hash from &username_to_idmap()
 5402:    $line            - number of current scanline
 5403:  
 5404:   Returns:
 5405:    Either 'username:domain' or undef if unknown
 5406: 
 5407: =cut
 5408: 
 5409: sub scantron_find_student {
 5410:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
 5411:     my $scanID=$$scantron_record{'scantron.ID'};
 5412:     if ($scanID =~ /^\s*$/) {
 5413:  	return &scan_data($scan_data,"$line.user");
 5414:     }
 5415:     foreach my $id (keys(%$idmap)) {
 5416:  	if (lc($id) eq lc($scanID)) {
 5417:  	    return $$idmap{$id};
 5418:  	}
 5419:     }
 5420:     return undef;
 5421: }
 5422: 
 5423: =pod
 5424: 
 5425: =item scantron_filter
 5426: 
 5427:    Filter sub for lonnavmaps, filters out hidden resources if ignore
 5428:    hidden resources was selected
 5429: 
 5430: =cut
 5431: 
 5432: sub scantron_filter {
 5433:     my ($curres)=@_;
 5434: 
 5435:     if (ref($curres) && $curres->is_problem()) {
 5436: 	# if the user has asked to not have either hidden
 5437: 	# or 'randomout' controlled resources to be graded
 5438: 	# don't include them
 5439: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 5440: 	    && $curres->randomout) {
 5441: 	    return 0;
 5442: 	}
 5443: 	return 1;
 5444:     }
 5445:     return 0;
 5446: }
 5447: 
 5448: =pod
 5449: 
 5450: =item scantron_process_corrections
 5451: 
 5452:    Gets correction information out of submitted form data and corrects
 5453:    the scanline
 5454: 
 5455: =cut
 5456: 
 5457: sub scantron_process_corrections {
 5458:     my ($r) = @_;
 5459:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5460:     my ($scanlines,$scan_data)=&scantron_getfile();
 5461:     my $classlist=&Apache::loncoursedata::get_classlist();
 5462:     my $which=$env{'form.scantron_line'};
 5463:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
 5464:     my ($skip,$err,$errmsg);
 5465:     if ($env{'form.scantron_skip_record'}) {
 5466: 	$skip=1;
 5467:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
 5468: 	my $newstudent=$env{'form.scantron_username'}.':'.
 5469: 	    $env{'form.scantron_domain'};
 5470: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
 5471: 	($line,$err,$errmsg)=
 5472: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5473: 				     'ID',{'newid'=>$newid,
 5474: 				    'username'=>$env{'form.scantron_username'},
 5475: 				    'domain'=>$env{'form.scantron_domain'}});
 5476:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
 5477: 	my $resolution=$env{'form.scantron_CODE_resolution'};
 5478: 	my $newCODE;
 5479: 	my %args;
 5480: 	if      ($resolution eq 'use_unfound') {
 5481: 	    $newCODE='use_unfound';
 5482: 	} elsif ($resolution eq 'use_found') {
 5483: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
 5484: 	} elsif ($resolution eq 'use_typed') {
 5485: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
 5486: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
 5487: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
 5488: 	}
 5489: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
 5490: 	    $args{'CODE_ignore_dup'}=1;
 5491: 	}
 5492: 	$args{'CODE'}=$newCODE;
 5493: 	($line,$err,$errmsg)=
 5494: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
 5495: 				     'CODE',\%args);
 5496:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
 5497: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
 5498: 	    ($line,$err,$errmsg)=
 5499: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
 5500: 					 $which,'answer',
 5501: 					 { 'question'=>$question,
 5502: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
 5503: 	    if ($err) { last; }
 5504: 	}
 5505:     }
 5506:     if ($err) {
 5507: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
 5508:     } else {
 5509: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
 5510: 	&scantron_putfile($scanlines,$scan_data);
 5511:     }
 5512: }
 5513: 
 5514: =pod
 5515: 
 5516: =item reset_skipping_status
 5517: 
 5518:    Forgets the current set of remember skipped scanlines (and thus
 5519:    reverts back to considering all lines in the
 5520:    scantron_skipped_<filename> file)
 5521: 
 5522: =cut
 5523: 
 5524: sub reset_skipping_status {
 5525:     my ($scanlines,$scan_data)=&scantron_getfile();
 5526:     &scan_data($scan_data,'remember_skipping',undef,1);
 5527:     &scantron_putfile(undef,$scan_data);
 5528: }
 5529: 
 5530: =pod
 5531: 
 5532: =item start_skipping
 5533: 
 5534:    Marks a scanline to be skipped. 
 5535: 
 5536: =cut
 5537: 
 5538: sub start_skipping {
 5539:     my ($scan_data,$i)=@_;
 5540:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5541:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
 5542: 	$remembered{$i}=2;
 5543:     } else {
 5544: 	$remembered{$i}=1;
 5545:     }
 5546:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
 5547: }
 5548: 
 5549: =pod
 5550: 
 5551: =item should_be_skipped
 5552: 
 5553:    Checks whether a scanline should be skipped.
 5554: 
 5555: =cut
 5556: 
 5557: sub should_be_skipped {
 5558:     my ($scanlines,$scan_data,$i)=@_;
 5559:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
 5560: 	# not redoing old skips
 5561: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
 5562: 	return 0;
 5563:     }
 5564:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
 5565: 
 5566:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
 5567: 	return 0;
 5568:     }
 5569:     return 1;
 5570: }
 5571: 
 5572: =pod
 5573: 
 5574: =item remember_current_skipped
 5575: 
 5576:    Discovers what scanlines are in the scantron_skipped_<filename>
 5577:    file and remembers them into scan_data for later use.
 5578: 
 5579: =cut
 5580: 
 5581: sub remember_current_skipped {
 5582:     my ($scanlines,$scan_data)=&scantron_getfile();
 5583:     my %to_remember;
 5584:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 5585: 	if ($scanlines->{'skipped'}[$i]) {
 5586: 	    $to_remember{$i}=1;
 5587: 	}
 5588:     }
 5589: 
 5590:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
 5591:     &scantron_putfile(undef,$scan_data);
 5592: }
 5593: 
 5594: =pod
 5595: 
 5596: =item check_for_error
 5597: 
 5598:     Checks if there was an error when attempting to remove a specific
 5599:     scantron_.. bubble sheet data file. Prints out an error if
 5600:     something went wrong.
 5601: 
 5602: =cut
 5603: 
 5604: sub check_for_error {
 5605:     my ($r,$result)=@_;
 5606:     if ($result ne 'ok' && $result ne 'not_found' ) {
 5607: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
 5608:     }
 5609: }
 5610: 
 5611: =pod
 5612: 
 5613: =item scantron_warning_screen
 5614: 
 5615:    Interstitial screen to make sure the operator has selected the
 5616:    correct options before we start the validation phase.
 5617: 
 5618: =cut
 5619: 
 5620: sub scantron_warning_screen {
 5621:     my ($button_text)=@_;
 5622:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
 5623:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 5624:     my $CODElist;
 5625:     if ($scantron_config{'CODElocation'} &&
 5626: 	$scantron_config{'CODEstart'} &&
 5627: 	$scantron_config{'CODElength'}) {
 5628: 	$CODElist=$env{'form.scantron_CODElist'};
 5629: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
 5630: 	$CODElist=
 5631: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
 5632: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
 5633:     }
 5634:     return (<<STUFF);
 5635: <p>
 5636: <span class="LC_warning">Please double check the information
 5637:                  below before clicking on '$button_text'</span>
 5638: </p>
 5639: <table>
 5640: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
 5641: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
 5642: $CODElist
 5643: </table>
 5644: <br />
 5645: <p> If this information is correct, please click on '$button_text'.</p>
 5646: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
 5647: 
 5648: <br />
 5649: STUFF
 5650: }
 5651: 
 5652: =pod
 5653: 
 5654: =item scantron_do_warning
 5655: 
 5656:    Check if the operator has picked something for all required
 5657:    fields. Error out if something is missing.
 5658: 
 5659: =cut
 5660: 
 5661: sub scantron_do_warning {
 5662:     my ($r)=@_;
 5663:     my ($symb)=&get_symb($r);
 5664:     if (!$symb) {return '';}
 5665:     my $default_form_data=&defaultFormData($symb);
 5666:     $r->print(&scantron_form_start().$default_form_data);
 5667:     if ( $env{'form.selectpage'} eq '' ||
 5668: 	 $env{'form.scantron_selectfile'} eq '' ||
 5669: 	 $env{'form.scantron_format'} eq '' ) {
 5670: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
 5671: 	if ( $env{'form.selectpage'} eq '') {
 5672: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
 5673: 	} 
 5674: 	if ( $env{'form.scantron_selectfile'} eq '') {
 5675: 	    $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
 5676: 	} 
 5677: 	if ( $env{'form.scantron_format'} eq '') {
 5678: 	    $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
 5679: 	} 
 5680:     } else {
 5681: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
 5682: 	$r->print(<<STUFF);
 5683: $warning
 5684: <input type="submit" name="submit" value="Grading: Validate Records" />
 5685: <input type="hidden" name="command" value="scantron_validate" />
 5686: STUFF
 5687:     }
 5688:     $r->print("</form><br />".&show_grading_menu_form($symb));
 5689:     return '';
 5690: }
 5691: 
 5692: =pod
 5693: 
 5694: =item scantron_form_start
 5695: 
 5696:     html hidden input for remembering all selected grading options
 5697: 
 5698: =cut
 5699: 
 5700: sub scantron_form_start {
 5701:     my ($max_bubble)=@_;
 5702:     my $result= <<SCANTRONFORM;
 5703: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 5704:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
 5705:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
 5706:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
 5707:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
 5708:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
 5709:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
 5710:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
 5711:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
 5712:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
 5713: SCANTRONFORM
 5714: 
 5715:   my $line = 0;
 5716:     while (defined($env{"form.scantron.bubblelines.$line"})) {
 5717:        my $chunk =
 5718: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
 5719:        $chunk +=
 5720: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line'." value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
 5721:        $result .= $chunk;
 5722:        $line++;
 5723:    }
 5724:     return $result;
 5725: }
 5726: 
 5727: =pod
 5728: 
 5729: =item scantron_validate_file
 5730: 
 5731:     Dispatch routine for doing validation of a bubble sheet data file.
 5732: 
 5733:     Also processes any necessary information resets that need to
 5734:     occur before validation begins (ignore previous corrections,
 5735:     restarting the skipped records processing)
 5736: 
 5737: =cut
 5738: 
 5739: sub scantron_validate_file {
 5740:     my ($r) = @_;
 5741:     my ($symb)=&get_symb($r);
 5742:     if (!$symb) {return '';}
 5743:     my $default_form_data=&defaultFormData($symb);
 5744:     
 5745:     # do the detection of only doing skipped records first befroe we delete
 5746:     # them when doing the corrections reset
 5747:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
 5748: 	&reset_skipping_status();
 5749:     }
 5750:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
 5751: 	&remember_current_skipped();
 5752: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
 5753:     }
 5754: 
 5755:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
 5756: 	&check_for_error($r,&scantron_remove_file('corrected'));
 5757: 	&check_for_error($r,&scantron_remove_file('skipped'));
 5758: 	&check_for_error($r,&scantron_remove_scan_data());
 5759: 	$env{'form.scantron_options_ignore'}='done';
 5760:     }
 5761: 
 5762:     if ($env{'form.scantron_corrections'}) {
 5763: 	&scantron_process_corrections($r);
 5764:     }
 5765:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
 5766:     #get the student pick code ready
 5767:     $r->print(&Apache::loncommon::studentbrowser_javascript());
 5768:     my $max_bubble=&scantron_get_maxbubble();
 5769:     my $result=&scantron_form_start($max_bubble).$default_form_data;
 5770:     $r->print($result);
 5771:     
 5772:     my @validate_phases=( 'sequence',
 5773: 			  'ID',
 5774: 			  'CODE',
 5775: 			  'doublebubble',
 5776: 			  'missingbubbles');
 5777:     if (!$env{'form.validatepass'}) {
 5778: 	$env{'form.validatepass'} = 0;
 5779:     }
 5780:     my $currentphase=$env{'form.validatepass'};
 5781: 
 5782:     my $stop=0;
 5783:     while (!$stop && $currentphase < scalar(@validate_phases)) {
 5784: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
 5785: 	$r->rflush();
 5786: 	my $which="scantron_validate_".$validate_phases[$currentphase];
 5787: 	{
 5788: 	    no strict 'refs';
 5789: 	    ($stop,$currentphase)=&$which($r,$currentphase);
 5790: 	}
 5791:     }
 5792:     if (!$stop) {
 5793: 	my $warning=&scantron_warning_screen('Start Grading');
 5794: 	$r->print(<<STUFF);
 5795: Validation process complete.<br />
 5796: $warning
 5797: <input type="submit" name="submit" value="Start Grading" />
 5798: <input type="hidden" name="command" value="scantron_process" />
 5799: STUFF
 5800: 
 5801:     } else {
 5802: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
 5803: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
 5804:     }
 5805:     if ($stop) {
 5806: 	if ($validate_phases[$currentphase] eq 'sequence') {
 5807: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
 5808: 	    $r->print(' this error <br />');
 5809: 
 5810: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
 5811: 	} else {
 5812: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
 5813: 	    $r->print(' using corrected info <br />');
 5814: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
 5815: 	    $r->print(" this scanline saving it for later.");
 5816: 	}
 5817:     }
 5818:     $r->print(" </form><br />".&show_grading_menu_form($symb));
 5819:     return '';
 5820: }
 5821: 
 5822: 
 5823: =pod
 5824: 
 5825: =item scantron_remove_file
 5826: 
 5827:    Removes the requested bubble sheet data file, makes sure that
 5828:    scantron_original_<filename> is never removed
 5829: 
 5830: 
 5831: =cut
 5832: 
 5833: sub scantron_remove_file {
 5834:     my ($which)=@_;
 5835:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5836:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5837:     my $file='scantron_';
 5838:     if ($which eq 'corrected' || $which eq 'skipped') {
 5839: 	$file.=$which.'_';
 5840:     } else {
 5841: 	return 'refused';
 5842:     }
 5843:     $file.=$env{'form.scantron_selectfile'};
 5844:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
 5845: }
 5846: 
 5847: 
 5848: =pod
 5849: 
 5850: =item scantron_remove_scan_data
 5851: 
 5852:    Removes all scan_data correction for the requested bubble sheet
 5853:    data file.  (In the case that both the are doing skipped records we need
 5854:    to remember the old skipped lines for the time being so that element
 5855:    persists for a while.)
 5856: 
 5857: =cut
 5858: 
 5859: sub scantron_remove_scan_data {
 5860:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5861:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5862:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
 5863:     my @todelete;
 5864:     my $filename=$env{'form.scantron_selectfile'};
 5865:     foreach my $key (@keys) {
 5866: 	if ($key=~/^\Q$filename\E_/) {
 5867: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
 5868: 		$key=~/remember_skipping/) {
 5869: 		next;
 5870: 	    }
 5871: 	    push(@todelete,$key);
 5872: 	}
 5873:     }
 5874:     my $result;
 5875:     if (@todelete) {
 5876: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
 5877:     }
 5878:     return $result;
 5879: }
 5880: 
 5881: 
 5882: =pod
 5883: 
 5884: =item scantron_getfile
 5885: 
 5886:     Fetches the requested bubble sheet data file (all 3 versions), and
 5887:     the scan_data hash
 5888:   
 5889:   Arguments:
 5890:     None
 5891: 
 5892:   Returns:
 5893:     2 hash references
 5894: 
 5895:      - first one has 
 5896:          orig      -
 5897:          corrected -
 5898:          skipped   -  each of which points to an array ref of the specified
 5899:                       file broken up into individual lines
 5900:          count     - number of scanlines
 5901:  
 5902:      - second is the scan_data hash possible keys are
 5903:        ($number refers to scanline numbered $number and thus the key affects
 5904:         only that scanline
 5905:         $bubline refers to the specific bubble line element and the aspects
 5906:         refers to that specific bubble line element)
 5907: 
 5908:        $number.user - username:domain to use
 5909:        $number.CODE_ignore_dup 
 5910:                     - ignore the duplicate CODE error 
 5911:        $number.useCODE
 5912:                     - use the CODE in the scanline as is
 5913:        $number.no_bubble.$bubline
 5914:                     - it is valid that there is no bubbled in bubble
 5915:                       at $number $bubline
 5916:        remember_skipping
 5917:                     - a frozen hash containing keys of $number and values
 5918:                       of either 
 5919:                         1 - we are on a 'do skipped records pass' and plan
 5920:                             on processing this line
 5921:                         2 - we are on a 'do skipped records pass' and this
 5922:                             scanline has been marked to skip yet again
 5923: 
 5924: =cut
 5925: 
 5926: sub scantron_getfile {
 5927:     #FIXME really would prefer a scantron directory
 5928:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5929:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5930:     my $lines;
 5931:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 5932: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
 5933:     my %scanlines;
 5934:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
 5935:     my $temp=$scanlines{'orig'};
 5936:     $scanlines{'count'}=$#$temp;
 5937: 
 5938:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 5939: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
 5940:     if ($lines eq '-1') {
 5941: 	$scanlines{'corrected'}=[];
 5942:     } else {
 5943: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
 5944:     }
 5945:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
 5946: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
 5947:     if ($lines eq '-1') {
 5948: 	$scanlines{'skipped'}=[];
 5949:     } else {
 5950: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
 5951:     }
 5952:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
 5953:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
 5954:     my %scan_data = @tmp;
 5955:     return (\%scanlines,\%scan_data);
 5956: }
 5957: 
 5958: =pod
 5959: 
 5960: =item lonnet_putfile
 5961: 
 5962:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
 5963: 
 5964:  Arguments:
 5965:    $contents - data to store
 5966:    $filename - filename to store $contents into
 5967: 
 5968:  Returns:
 5969:    result value from &Apache::lonnet::finishuserfileupload
 5970: 
 5971: =cut
 5972: 
 5973: sub lonnet_putfile {
 5974:     my ($contents,$filename)=@_;
 5975:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5976:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5977:     $env{'form.sillywaytopassafilearound'}=$contents;
 5978:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
 5979: 
 5980: }
 5981: 
 5982: =pod
 5983: 
 5984: =item scantron_putfile
 5985: 
 5986:     Stores the current version of the bubble sheet data files, and the
 5987:     scan_data hash. (Does not modify the original version only the
 5988:     corrected and skipped versions.
 5989: 
 5990:  Arguments:
 5991:     $scanlines - hash ref that looks like the first return value from
 5992:                  &scantron_getfile()
 5993:     $scan_data - hash ref that looks like the second return value from
 5994:                  &scantron_getfile()
 5995: 
 5996: =cut
 5997: 
 5998: sub scantron_putfile {
 5999:     my ($scanlines,$scan_data) = @_;
 6000:     #FIXME really would prefer a scantron directory
 6001:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6002:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6003:     if ($scanlines) {
 6004: 	my $prefix='scantron_';
 6005: # no need to update orig, shouldn't change
 6006: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
 6007: #		    $env{'form.scantron_selectfile'});
 6008: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
 6009: 			$prefix.'corrected_'.
 6010: 			$env{'form.scantron_selectfile'});
 6011: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
 6012: 			$prefix.'skipped_'.
 6013: 			$env{'form.scantron_selectfile'});
 6014:     }
 6015:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
 6016: }
 6017: 
 6018: =pod
 6019: 
 6020: =item scantron_get_line
 6021: 
 6022:    Returns the correct version of the scanline
 6023: 
 6024:  Arguments:
 6025:     $scanlines - hash ref that looks like the first return value from
 6026:                  &scantron_getfile()
 6027:     $scan_data - hash ref that looks like the second return value from
 6028:                  &scantron_getfile()
 6029:     $i         - number of the requested line (starts at 0)
 6030: 
 6031:  Returns:
 6032:    A scanline, (either the original or the corrected one if it
 6033:    exists), or undef if the requested scanline should be
 6034:    skipped. (Either because it's an skipped scanline, or it's an
 6035:    unskipped scanline and we are not doing a 'do skipped scanlines'
 6036:    pass.
 6037: 
 6038: =cut
 6039: 
 6040: sub scantron_get_line {
 6041:     my ($scanlines,$scan_data,$i)=@_;
 6042:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
 6043:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
 6044:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
 6045:     return $scanlines->{'orig'}[$i]; 
 6046: }
 6047: 
 6048: =pod
 6049: 
 6050: =item scantron_todo_count
 6051: 
 6052:     Counts the number of scanlines that need processing.
 6053: 
 6054:  Arguments:
 6055:     $scanlines - hash ref that looks like the first return value from
 6056:                  &scantron_getfile()
 6057:     $scan_data - hash ref that looks like the second return value from
 6058:                  &scantron_getfile()
 6059: 
 6060:  Returns:
 6061:     $count - number of scanlines to process
 6062: 
 6063: =cut
 6064: 
 6065: sub get_todo_count {
 6066:     my ($scanlines,$scan_data)=@_;
 6067:     my $count=0;
 6068:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6069: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6070: 	if ($line=~/^[\s\cz]*$/) { next; }
 6071: 	$count++;
 6072:     }
 6073:     return $count;
 6074: }
 6075: 
 6076: =pod
 6077: 
 6078: =item scantron_put_line
 6079: 
 6080:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
 6081:     data file.
 6082: 
 6083:  Arguments:
 6084:     $scanlines - hash ref that looks like the first return value from
 6085:                  &scantron_getfile()
 6086:     $scan_data - hash ref that looks like the second return value from
 6087:                  &scantron_getfile()
 6088:     $i         - line number to update
 6089:     $newline   - contents of the updated scanline
 6090:     $skip      - if true make the line for skipping and update the
 6091:                  'skipped' file
 6092: 
 6093: =cut
 6094: 
 6095: sub scantron_put_line {
 6096:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
 6097:     if ($skip) {
 6098: 	$scanlines->{'skipped'}[$i]=$newline;
 6099: 	&start_skipping($scan_data,$i);
 6100: 	return;
 6101:     }
 6102:     $scanlines->{'corrected'}[$i]=$newline;
 6103: }
 6104: 
 6105: =pod
 6106: 
 6107: =item scantron_clear_skip
 6108: 
 6109:    Remove a line from the 'skipped' file
 6110: 
 6111:  Arguments:
 6112:     $scanlines - hash ref that looks like the first return value from
 6113:                  &scantron_getfile()
 6114:     $scan_data - hash ref that looks like the second return value from
 6115:                  &scantron_getfile()
 6116:     $i         - line number to update
 6117: 
 6118: =cut
 6119: 
 6120: sub scantron_clear_skip {
 6121:     my ($scanlines,$scan_data,$i)=@_;
 6122:     if (exists($scanlines->{'skipped'}[$i])) {
 6123: 	undef($scanlines->{'skipped'}[$i]);
 6124: 	return 1;
 6125:     }
 6126:     return 0;
 6127: }
 6128: 
 6129: =pod
 6130: 
 6131: =item scantron_filter_not_exam
 6132: 
 6133:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
 6134:    filter out resources that are not marked as 'exam' mode
 6135: 
 6136: =cut
 6137: 
 6138: sub scantron_filter_not_exam {
 6139:     my ($curres)=@_;
 6140:     
 6141:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
 6142: 	# if the user has asked to not have either hidden
 6143: 	# or 'randomout' controlled resources to be graded
 6144: 	# don't include them
 6145: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
 6146: 	    && $curres->randomout) {
 6147: 	    return 0;
 6148: 	}
 6149: 	return 1;
 6150:     }
 6151:     return 0;
 6152: }
 6153: 
 6154: =pod
 6155: 
 6156: =item scantron_validate_sequence
 6157: 
 6158:     Validates the selected sequence, checking for resource that are
 6159:     not set to exam mode.
 6160: 
 6161: =cut
 6162: 
 6163: sub scantron_validate_sequence {
 6164:     my ($r,$currentphase) = @_;
 6165: 
 6166:     my $navmap=Apache::lonnavmaps::navmap->new();
 6167:     my (undef,undef,$sequence)=
 6168: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6169: 
 6170:     my $map=$navmap->getResourceByUrl($sequence);
 6171: 
 6172:     $r->print('<input type="hidden" name="validate_sequence_exam"
 6173:                                     value="ignore" />');
 6174:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
 6175: 	my @resources=
 6176: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
 6177: 	if (@resources) {
 6178: 	    $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>");
 6179: 	    return (1,$currentphase);
 6180: 	}
 6181:     }
 6182: 
 6183:     return (0,$currentphase+1);
 6184: }
 6185: 
 6186: =pod
 6187: 
 6188: =item scantron_validate_ID
 6189: 
 6190:    Validates all scanlines in the selected file to not have any
 6191:    invalid or underspecified student IDs
 6192: 
 6193: =cut
 6194: 
 6195: sub scantron_validate_ID {
 6196:     my ($r,$currentphase) = @_;
 6197:     
 6198:     #get student info
 6199:     my $classlist=&Apache::loncoursedata::get_classlist();
 6200:     my %idmap=&username_to_idmap($classlist);
 6201: 
 6202:     #get scantron line setup
 6203:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6204:     my ($scanlines,$scan_data)=&scantron_getfile();
 6205:     
 6206:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
 6207: 
 6208:     my %found=('ids'=>{},'usernames'=>{});
 6209:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6210: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6211: 	if ($line=~/^[\s\cz]*$/) { next; }
 6212: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6213: 						 $scan_data);
 6214: 	my $id=$$scan_record{'scantron.ID'};
 6215: 	my $found;
 6216: 	foreach my $checkid (keys(%idmap)) {
 6217: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
 6218: 	}
 6219: 	if ($found) {
 6220: 	    my $username=$idmap{$found};
 6221: 	    if ($found{'ids'}{$found}) {
 6222: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6223: 					 $line,'duplicateID',$found);
 6224: 		return(1,$currentphase);
 6225: 	    } elsif ($found{'usernames'}{$username}) {
 6226: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6227: 					 $line,'duplicateID',$username);
 6228: 		return(1,$currentphase);
 6229: 	    }
 6230: 	    #FIXME store away line we previously saw the ID on to use above
 6231: 	    $found{'ids'}{$found}++;
 6232: 	    $found{'usernames'}{$username}++;
 6233: 	} else {
 6234: 	    if ($id =~ /^\s*$/) {
 6235: 		my $username=&scan_data($scan_data,"$i.user");
 6236: 		if (defined($username) && $found{'usernames'}{$username}) {
 6237: 		    &scantron_get_correction($r,$i,$scan_record,
 6238: 					     \%scantron_config,
 6239: 					     $line,'duplicateID',$username);
 6240: 		    return(1,$currentphase);
 6241: 		} elsif (!defined($username)) {
 6242: 		    &scantron_get_correction($r,$i,$scan_record,
 6243: 					     \%scantron_config,
 6244: 					     $line,'incorrectID');
 6245: 		    return(1,$currentphase);
 6246: 		}
 6247: 		$found{'usernames'}{$username}++;
 6248: 	    } else {
 6249: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6250: 					 $line,'incorrectID');
 6251: 		return(1,$currentphase);
 6252: 	    }
 6253: 	}
 6254:     }
 6255: 
 6256:     return (0,$currentphase+1);
 6257: }
 6258: 
 6259: =pod
 6260: 
 6261: =item scantron_get_correction
 6262: 
 6263:    Builds the interface screen to interact with the operator to fix a
 6264:    specific error condition in a specific scanline
 6265: 
 6266:  Arguments:
 6267:     $r           - Apache request object
 6268:     $i           - number of the current scanline
 6269:     $scan_record - hash ref as returned from &scantron_parse_scanline()
 6270:     $scan_config - hash ref as returned from &get_scantron_config()
 6271:     $line        - full contents of the current scanline
 6272:     $error       - error condition, valid values are
 6273:                    'incorrectCODE', 'duplicateCODE',
 6274:                    'doublebubble', 'missingbubble',
 6275:                    'duplicateID', 'incorrectID'
 6276:     $arg         - extra information needed
 6277:        For errors:
 6278:          - duplicateID   - paper number that this studentID was seen before on
 6279:          - duplicateCODE - array ref of the paper numbers this CODE was
 6280:                            seen on before
 6281:          - incorrectCODE - current incorrect CODE 
 6282:          - doublebubble  - array ref of the bubble lines that have double
 6283:                            bubble errors
 6284:          - missingbubble - array ref of the bubble lines that have missing
 6285:                            bubble errors
 6286: 
 6287: =cut
 6288: 
 6289: sub scantron_get_correction {
 6290:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
 6291: 
 6292: #FIXME in the case of a duplicated ID the previous line, probaly need
 6293: #to show both the current line and the previous one and allow skipping
 6294: #the previous one or the current one
 6295: 
 6296:     $r->print("<p><b>An error was detected ($error)</b>");
 6297:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
 6298: 	$r->print(" for PaperID <tt>".
 6299: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
 6300:     } else {
 6301: 	$r->print(" in scanline $i <pre>".
 6302: 		  $line."</pre> \n");
 6303:     }
 6304:     my $message="<p>The ID on the form is  <tt>".
 6305: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
 6306: 	"The name on the paper is ".
 6307: 	$$scan_record{'scantron.LastName'}.",".
 6308: 	$$scan_record{'scantron.FirstName'}."</p>";
 6309: 
 6310:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
 6311:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
 6312:     if ($error =~ /ID$/) {
 6313: 	if ($error eq 'incorrectID') {
 6314: 	    $r->print("The encoded ID is not in the classlist</p>\n");
 6315: 	} elsif ($error eq 'duplicateID') {
 6316: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
 6317: 	}
 6318: 	$r->print($message);
 6319: 	$r->print("<p>How should I handle this? <br /> \n");
 6320: 	$r->print("\n<ul><li> ");
 6321: 	#FIXME it would be nice if this sent back the user ID and
 6322: 	#could do partial userID matches
 6323: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
 6324: 				       'scantron_username','scantron_domain'));
 6325: 	$r->print(": <input type='text' name='scantron_username' value='' />");
 6326: 	$r->print("\n@".
 6327: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
 6328: 
 6329: 	$r->print('</li>');
 6330:     } elsif ($error =~ /CODE$/) {
 6331: 	if ($error eq 'incorrectCODE') {
 6332: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
 6333: 	} elsif ($error eq 'duplicateCODE') {
 6334: 	    $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");
 6335: 	}
 6336: 	$r->print("<p>The CODE on the form is  <tt>'".
 6337: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
 6338: 	$r->print($message);
 6339: 	$r->print("<p>How should I handle this? <br /> \n");
 6340: 	$r->print("\n<br /> ");
 6341: 	my $i=0;
 6342: 	if ($error eq 'incorrectCODE' 
 6343: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
 6344: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
 6345: 	    if ($closest > 0) {
 6346: 		foreach my $testcode (@{$closest}) {
 6347: 		    my $checked='';
 6348: 		    if (!$i) { $checked=' checked="checked" '; }
 6349: 		    $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' />");
 6350: 		    $r->print("\n<br />");
 6351: 		    $i++;
 6352: 		}
 6353: 	    }
 6354: 	}
 6355: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
 6356: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
 6357: 	    $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>");
 6358: 	    $r->print("\n<br />");
 6359: 	}
 6360: 
 6361: 	$r->print(<<ENDSCRIPT);
 6362: <script type="text/javascript">
 6363: function change_radio(field) {
 6364:     var slct=document.scantronupload.scantron_CODE_resolution;
 6365:     var i;
 6366:     for (i=0;i<slct.length;i++) {
 6367:         if (slct[i].value==field) { slct[i].checked=true; }
 6368:     }
 6369: }
 6370: </script>
 6371: ENDSCRIPT
 6372: 	my $href="/adm/pickcode?".
 6373: 	   "form=".&escape("scantronupload").
 6374: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
 6375: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
 6376: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
 6377: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
 6378: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
 6379: 	    $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')\" />");
 6380: 	    $r->print("\n<br />");
 6381: 	}
 6382: 	$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.");
 6383: 	$r->print("\n<br /><br />");
 6384:     } elsif ($error eq 'doublebubble') {
 6385: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
 6386: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6387: 		  join(',',@{$arg}).'" />');
 6388: 	$r->print($message);
 6389: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
 6390: 	foreach my $question (@{$arg}) {
 6391: 
 6392: 	    my $selected  = &get_response_bubbles($scan_record, $question);
 6393: 	    &scantron_bubble_selector($r,$scan_config,$question,
 6394: 				      split('',$selected));
 6395: 	}
 6396:     } elsif ($error eq 'missingbubble') {
 6397: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
 6398: 	$r->print($message);
 6399: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
 6400: 	$r->print("Some questions have no scanned bubbles\n");
 6401: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
 6402: 		  join(',',@{$arg}).'" />');
 6403: 	foreach my $question (@{$arg}) {
 6404: 	    my $selected = &get_response_bubbles($scan_record, $quesion);
 6405: 	    &scantron_bubble_selector($r,$scan_config,$question);
 6406: 	}
 6407:     } else {
 6408: 	$r->print("\n<ul>");
 6409:     }
 6410:     $r->print("\n</li></ul>");
 6411: 
 6412: }
 6413: 
 6414: =pod
 6415: 
 6416: =item scantron_bubble_selector
 6417:   
 6418:    Generates the html radiobuttons to correct a single bubble line
 6419:    possibly showing the existing the selected bubbles if known
 6420: 
 6421:  Arguments:
 6422:     $r           - Apache request object
 6423:     $scan_config - hash from &get_scantron_config()
 6424:     $quest       - number of the bubble line to make a corrector for
 6425:     $selected    - array of letters of previously selected bubbles
 6426: 
 6427: =cut
 6428: 
 6429: sub scantron_bubble_selector {
 6430:     my ($r,$scan_config,$quest,@selected)=@_;
 6431:     my $max=$$scan_config{'Qlength'};
 6432: 
 6433:     my $scmode=$$scan_config{'Qon'};
 6434: 
 6435: 
 6436:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
 6437: 
 6438: 
 6439:     my $lines = $bubble_lines_per_response{$quest};
 6440: 
 6441:     my $total_lines = $lines*2;
 6442:     my @alphabet=('A'..'Z');
 6443:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
 6444: 
 6445:     for (my $l = 0; $l < $lines; $l++) {
 6446: 	if ($l != 0) {
 6447: 	    $r->print('<tr>');
 6448: 	}
 6449: 
 6450: 	# FIXME:  This loop probably has to be considerably more clever for
 6451: 	#  multiline bubbles: User can multibubble by having bubbles in
 6452: 	#  several lines.  User can skip lines legitimately etc. etc.
 6453: 
 6454: 	for (my $i=0;$i<$max;$i++) {
 6455: 	    $r->print("\n".'<td align="center">');
 6456: 	    if ($selected[0] eq $alphabet[$i]) { 
 6457: 		$r->print('X'); 
 6458: 		shift(@selected) ;
 6459: 	    } else { 
 6460: 		$r->print('&nbsp;'); 
 6461: 	    }
 6462: 	    $r->print('</td>');
 6463: 	    
 6464: 	}
 6465: 
 6466: 	if ($l == 0) {
 6467: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
 6468: 
 6469: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
 6470: 	      $quest.'" value="none" /> No bubble </label></td>');
 6471: 	
 6472: 	}
 6473: 
 6474: 	$r->print('</tr><tr>');
 6475: 
 6476: 	# FIXME: This may have to be a bit more clever for
 6477: 	#        multiline questions (different values e.g..).
 6478: 
 6479: 	for (my $i=0;$i<$max;$i++) {
 6480: 	    $r->print("\n".
 6481: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
 6482: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
 6483: 	}
 6484: 	$r->print('</tr>');
 6485: 
 6486: 	    
 6487:     }
 6488:     $r->print('</table>');
 6489: }
 6490: 
 6491: =pod
 6492: 
 6493: =item num_matches
 6494: 
 6495:    Counts the number of characters that are the same between the two arguments.
 6496: 
 6497:  Arguments:
 6498:    $orig - CODE from the scanline
 6499:    $code - CODE to match against
 6500: 
 6501:  Returns:
 6502:    $count - integer count of the number of same characters between the
 6503:             two arguments
 6504: 
 6505: =cut
 6506: 
 6507: sub num_matches {
 6508:     my ($orig,$code) = @_;
 6509:     my @code=split(//,$code);
 6510:     my @orig=split(//,$orig);
 6511:     my $same=0;
 6512:     for (my $i=0;$i<scalar(@code);$i++) {
 6513: 	if ($code[$i] eq $orig[$i]) { $same++; }
 6514:     }
 6515:     return $same;
 6516: }
 6517: 
 6518: =pod
 6519: 
 6520: =item scantron_get_closely_matching_CODEs
 6521: 
 6522:    Cycles through all CODEs and finds the set that has the greatest
 6523:    number of same characters as the provided CODE
 6524: 
 6525:  Arguments:
 6526:    $allcodes - hash ref returned by &get_codes()
 6527:    $CODE     - CODE from the current scanline
 6528: 
 6529:  Returns:
 6530:    2 element list
 6531:     - first elements is number of how closely matching the best fit is 
 6532:       (5 means best set has 5 matching characters)
 6533:     - second element is an arrary ref containing the set of valid CODEs
 6534:       that best fit the passed in CODE
 6535: 
 6536: =cut
 6537: 
 6538: sub scantron_get_closely_matching_CODEs {
 6539:     my ($allcodes,$CODE)=@_;
 6540:     my @CODEs;
 6541:     foreach my $testcode (sort(keys(%{$allcodes}))) {
 6542: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
 6543:     }
 6544: 
 6545:     return ($#CODEs,$CODEs[-1]);
 6546: }
 6547: 
 6548: =pod
 6549: 
 6550: =item get_codes
 6551: 
 6552:    Builds a hash which has keys of all of the valid CODEs from the selected
 6553:    set of remembered CODEs.
 6554: 
 6555:  Arguments:
 6556:   $old_name - name of the set of remembered CODEs
 6557:   $cdom     - domain of the course
 6558:   $cnum     - internal course name
 6559: 
 6560:  Returns:
 6561:   %allcodes - keys are the valid CODEs, values are all 1
 6562: 
 6563: =cut
 6564: 
 6565: sub get_codes {
 6566:     my ($old_name, $cdom, $cnum) = @_;
 6567:     if (!$old_name) {
 6568: 	$old_name=$env{'form.scantron_CODElist'};
 6569:     }
 6570:     if (!$cdom) {
 6571: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
 6572:     }
 6573:     if (!$cnum) {
 6574: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
 6575:     }
 6576:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
 6577: 				    $cdom,$cnum);
 6578:     my %allcodes;
 6579:     if ($result{"type\0$old_name"} eq 'number') {
 6580: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
 6581:     } else {
 6582: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
 6583:     }
 6584:     return %allcodes;
 6585: }
 6586: 
 6587: =pod
 6588: 
 6589: =item scantron_validate_CODE
 6590: 
 6591:    Validates all scanlines in the selected file to not have any
 6592:    invalid or underspecified CODEs and that none of the codes are
 6593:    duplicated if this was requested.
 6594: 
 6595: =cut
 6596: 
 6597: sub scantron_validate_CODE {
 6598:     my ($r,$currentphase) = @_;
 6599:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6600:     if ($scantron_config{'CODElocation'} &&
 6601: 	$scantron_config{'CODEstart'} &&
 6602: 	$scantron_config{'CODElength'}) {
 6603: 	if (!defined($env{'form.scantron_CODElist'})) {
 6604: 	    &FIXME_blow_up()
 6605: 	}
 6606:     } else {
 6607: 	return (0,$currentphase+1);
 6608:     }
 6609:     
 6610:     my %usedCODEs;
 6611: 
 6612:     my %allcodes=&get_codes();
 6613: 
 6614:     &scantron_get_maxbubble();	# parse needs the lines per response array.
 6615: 
 6616:     my ($scanlines,$scan_data)=&scantron_getfile();
 6617:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6618: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6619: 	if ($line=~/^[\s\cz]*$/) { next; }
 6620: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6621: 						 $scan_data);
 6622: 	my $CODE=$$scan_record{'scantron.CODE'};
 6623: 	my $error=0;
 6624: 	if (!&Apache::lonnet::validCODE($CODE)) {
 6625: 	    &scantron_get_correction($r,$i,$scan_record,
 6626: 				     \%scantron_config,
 6627: 				     $line,'incorrectCODE',\%allcodes);
 6628: 	    return(1,$currentphase);
 6629: 	}
 6630: 	if (%allcodes && !exists($allcodes{$CODE}) 
 6631: 	    && !$$scan_record{'scantron.useCODE'}) {
 6632: 	    &scantron_get_correction($r,$i,$scan_record,
 6633: 				     \%scantron_config,
 6634: 				     $line,'incorrectCODE',\%allcodes);
 6635: 	    return(1,$currentphase);
 6636: 	}
 6637: 	if (exists($usedCODEs{$CODE}) 
 6638: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
 6639: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
 6640: 	    &scantron_get_correction($r,$i,$scan_record,
 6641: 				     \%scantron_config,
 6642: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
 6643: 	    return(1,$currentphase);
 6644: 	}
 6645: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
 6646:     }
 6647:     return (0,$currentphase+1);
 6648: }
 6649: 
 6650: =pod
 6651: 
 6652: =item scantron_validate_doublebubble
 6653: 
 6654:    Validates all scanlines in the selected file to not have any
 6655:    bubble lines with multiple bubbles marked.
 6656: 
 6657: =cut
 6658: 
 6659: sub scantron_validate_doublebubble {
 6660:     my ($r,$currentphase) = @_;
 6661:     #get student info
 6662:     my $classlist=&Apache::loncoursedata::get_classlist();
 6663:     my %idmap=&username_to_idmap($classlist);
 6664: 
 6665:     #get scantron line setup
 6666:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6667:     my ($scanlines,$scan_data)=&scantron_getfile();
 6668: 
 6669:     &scantron_get_maxbubble();	# parse needs the bubble line array.
 6670: 
 6671:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6672: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6673: 	if ($line=~/^[\s\cz]*$/) { next; }
 6674: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6675: 						 $scan_data);
 6676: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
 6677: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
 6678: 				 'doublebubble',
 6679: 				 $$scan_record{'scantron.doubleerror'});
 6680:     	return (1,$currentphase);
 6681:     }
 6682:     return (0,$currentphase+1);
 6683: }
 6684: 
 6685: =pod
 6686: 
 6687: =item scantron_get_maxbubble
 6688: 
 6689:    Returns the maximum number of bubble lines that are expected to
 6690:    occur. Does this by walking the selected sequence rendering the
 6691:    resource and then checking &Apache::lonxml::get_problem_counter()
 6692:    for what the current value of the problem counter is.
 6693: 
 6694:    Caches the results to $env{'form.scantron_maxbubble'},
 6695:    $env{'form.scantron.bubble_lines.n'} and 
 6696:    $env{'form.scantron.first_bubble_line.n'}
 6697:    which are the total number of bubble, lines, the number of bubble
 6698:    lines for reponse n and number of the first bubble line for response n.
 6699: 
 6700: =cut
 6701: 
 6702: sub scantron_get_maxbubble {    
 6703: 
 6704:     if (defined($env{'form.scantron_maxbubble'}) &&
 6705: 	$env{'form.scantron_maxbubble'}) {
 6706: 	&restore_bubble_lines();
 6707: 	return $env{'form.scantron_maxbubble'};
 6708:     }
 6709: 
 6710:     my (undef, undef, $sequence) =
 6711: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6712: 
 6713:     my $navmap=Apache::lonnavmaps::navmap->new();
 6714:     my $map=$navmap->getResourceByUrl($sequence);
 6715:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 6716: 
 6717:     &Apache::lonxml::clear_problem_counter();
 6718: 
 6719:     my $uname       = $env{'form.student'};
 6720:     my $udom        = $env{'form.userdom'};
 6721:     my $cid         = $env{'request.course.id'};
 6722:     my $total_lines = 0;
 6723:     %bubble_lines_per_response = ();
 6724:     %first_bubble_line         = ();
 6725: 
 6726:   
 6727:     my $response_number = 0;
 6728:     my $bubble_line     = 0;
 6729:     foreach my $resource (@resources) {
 6730: 	my $symb = $resource->symb();
 6731: 	&Apache::lonxml::clear_bubble_lines_for_part();
 6732: 	my $result=&Apache::lonnet::ssi($resource->src(),
 6733: 					('symb' => $resource->symb()),
 6734: 					('grade_target' => 'analyze'),
 6735: 					('grade_courseid' => $cid),
 6736: 					('grade_domain' => $udom),
 6737: 					('grade_username' => $uname));
 6738: 	my (undef, $an) =
 6739: 	    split(/_HASH_REF__/,$result, 2);
 6740: 
 6741: 	my %analysis = &Apache::lonnet::str2hash($an);
 6742: 
 6743: 
 6744: 
 6745: 	foreach my $part_id (@{$analysis{'parts'}}) {
 6746: 	    my ($trash, $part) = split(/\./, $part_id);
 6747: 
 6748: 	    my $lines = $analysis{"$part_id.bubble_lines"}[0];
 6749: 
 6750: 	    # TODO - make this a persistent hash not an array.
 6751: 
 6752: 
 6753: 	    $first_bubble_line{$response_number}           = $bubble_line;
 6754: 	    $bubble_lines_per_response{$response_number}   = $lines;
 6755: 	    $response_number++;
 6756: 
 6757: 	    $bubble_line +=  $lines;
 6758: 	    $total_lines +=  $lines;
 6759: 	}
 6760: 
 6761:     }
 6762:     &Apache::lonnet::delenv('scantron\.');
 6763: 
 6764:     &save_bubble_lines();
 6765:     $env{'form.scantron_maxbubble'} =
 6766: 	$total_lines;
 6767:     return $env{'form.scantron_maxbubble'};
 6768: }
 6769: 
 6770: =pod
 6771: 
 6772: =item scantron_validate_missingbubbles
 6773: 
 6774:    Validates all scanlines in the selected file to not have any
 6775:     answers that don't have bubbles that have not been verified
 6776:     to be bubble free.
 6777: 
 6778: =cut
 6779: 
 6780: sub scantron_validate_missingbubbles {
 6781:     my ($r,$currentphase) = @_;
 6782:     #get student info
 6783:     my $classlist=&Apache::loncoursedata::get_classlist();
 6784:     my %idmap=&username_to_idmap($classlist);
 6785: 
 6786:     #get scantron line setup
 6787:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6788:     my ($scanlines,$scan_data)=&scantron_getfile();
 6789:     my $max_bubble=&scantron_get_maxbubble();
 6790:     if (!$max_bubble) { $max_bubble=2**31; }
 6791:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
 6792: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6793: 	if ($line=~/^[\s\cz]*$/) { next; }
 6794: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6795: 						 $scan_data);
 6796: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
 6797: 	my @to_correct;
 6798: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
 6799: 	    if ($missing > $max_bubble) { next; }
 6800: 	    push(@to_correct,$missing);
 6801: 	}
 6802: 	if (@to_correct) {
 6803: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
 6804: 				     $line,'missingbubble',\@to_correct);
 6805: 	    return (1,$currentphase);
 6806: 	}
 6807: 
 6808:     }
 6809:     return (0,$currentphase+1);
 6810: }
 6811: 
 6812: =pod
 6813: 
 6814: =item scantron_process_students
 6815: 
 6816:    Routine that does the actual grading of the bubble sheet information.
 6817: 
 6818:    The parsed scanline hash is added to %env 
 6819: 
 6820:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
 6821:    foreach resource , with the form data of
 6822: 
 6823: 	'submitted'     =>'scantron' 
 6824: 	'grade_target'  =>'grade',
 6825: 	'grade_username'=> username of student
 6826: 	'grade_domain'  => domain of student
 6827: 	'grade_courseid'=> of course
 6828: 	'grade_symb'    => symb of resource to grade
 6829: 
 6830:     This triggers a grading pass. The problem grading code takes care
 6831:     of converting the bubbled letter information (now in %env) into a
 6832:     valid submission.
 6833: 
 6834: =cut
 6835: 
 6836: sub scantron_process_students {
 6837:     my ($r) = @_;
 6838:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
 6839:     my ($symb)=&get_symb($r);
 6840:     if (!$symb) {return '';}
 6841:     my $default_form_data=&defaultFormData($symb);
 6842: 
 6843:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
 6844:     my ($scanlines,$scan_data)=&scantron_getfile();
 6845:     my $classlist=&Apache::loncoursedata::get_classlist();
 6846:     my %idmap=&username_to_idmap($classlist);
 6847:     my $navmap=Apache::lonnavmaps::navmap->new();
 6848:     my $map=$navmap->getResourceByUrl($sequence);
 6849:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
 6850: #    $r->print("geto ".scalar(@resources)."<br />");
 6851:     my $result= <<SCANTRONFORM;
 6852: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
 6853:   <input type="hidden" name="command" value="scantron_configphase" />
 6854:   $default_form_data
 6855: SCANTRONFORM
 6856:     $r->print($result);
 6857: 
 6858:     my @delayqueue;
 6859:     my %completedstudents;
 6860:     
 6861:     my $count=&get_todo_count($scanlines,$scan_data);
 6862:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
 6863:  				    'Scantron Progress',$count,
 6864: 				    'inline',undef,'scantronupload');
 6865:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 6866: 					  'Processing first student');
 6867:     my $start=&Time::HiRes::time();
 6868:     my $i=-1;
 6869:     my ($uname,$udom,$started);
 6870: 
 6871:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
 6872: 
 6873:     while ($i<$scanlines->{'count'}) {
 6874:  	($uname,$udom)=('','');
 6875:  	$i++;
 6876:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
 6877:  	if ($line=~/^[\s\cz]*$/) { next; }
 6878: 	if ($started) {
 6879: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 6880: 						     'last student');
 6881: 	}
 6882: 	$started=1;
 6883:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
 6884:  						 $scan_data);
 6885:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
 6886:  					      \%idmap,$i)) {
 6887:   	    &scantron_add_delay(\@delayqueue,$line,
 6888:  				'Unable to find a student that matches',1);
 6889:  	    next;
 6890:   	}
 6891:  	if (exists $completedstudents{$uname}) {
 6892:  	    &scantron_add_delay(\@delayqueue,$line,
 6893:  				'Student '.$uname.' has multiple sheets',2);
 6894:  	    next;
 6895:  	}
 6896:   	($uname,$udom)=split(/:/,$uname);
 6897: 
 6898: 	&Apache::lonxml::clear_problem_counter();
 6899:   	&Apache::lonnet::appenv(%$scan_record);
 6900: 
 6901: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
 6902: 	    &scantron_putfile($scanlines,$scan_data);
 6903: 	}
 6904: 	
 6905: 	my $i=0;
 6906: 	foreach my $resource (@resources) {
 6907: 	    $i++;
 6908: 	    my %form=('submitted'     =>'scantron',
 6909: 		      'grade_target'  =>'grade',
 6910: 		      'grade_username'=>$uname,
 6911: 		      'grade_domain'  =>$udom,
 6912: 		      'grade_courseid'=>$env{'request.course.id'},
 6913: 		      'grade_symb'    =>$resource->symb());
 6914: 	    if (exists($scan_record->{'scantron.CODE'})
 6915: 		&& 
 6916: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
 6917: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
 6918: 	    } else {
 6919: 		$form{'CODE'}='';
 6920: 	    }
 6921: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
 6922: 	    if ($result ne '') {
 6923: 	    }
 6924: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
 6925: 	}
 6926: 	$completedstudents{$uname}={'line'=>$line};
 6927: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
 6928:     } continue {
 6929: 	&Apache::lonxml::clear_problem_counter();
 6930: 	&Apache::lonnet::delenv('scantron\.');
 6931:     }
 6932:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 6933: #    my $lasttime = &Time::HiRes::time()-$start;
 6934: #    $r->print("<p>took $lasttime</p>");
 6935: 
 6936:     $r->print("</form>");
 6937:     $r->print(&show_grading_menu_form($symb));
 6938:     return '';
 6939: }
 6940: 
 6941: =pod
 6942: 
 6943: =item scantron_upload_scantron_data
 6944: 
 6945:     Creates the screen for adding a new bubble sheet data file to a course.
 6946: 
 6947: =cut
 6948: 
 6949: sub scantron_upload_scantron_data {
 6950:     my ($r)=@_;
 6951:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
 6952:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
 6953: 							  'domainid',
 6954: 							  'coursename');
 6955:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
 6956: 						   'domainid');
 6957:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 6958:     $r->print(<<UPLOAD);
 6959: <script type="text/javascript" language="javascript">
 6960:     function checkUpload(formname) {
 6961: 	if (formname.upfile.value == "") {
 6962: 	    alert("Please use the browse button to select a file from your local directory.");
 6963: 	    return false;
 6964: 	}
 6965: 	formname.submit();
 6966:     }
 6967: </script>
 6968: 
 6969: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
 6970: $default_form_data
 6971: <table>
 6972: <tr><td>$select_link </td></tr>
 6973: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
 6974: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
 6975: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
 6976: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
 6977: </table>
 6978: <input name='command' value='scantronupload_save' type='hidden' />
 6979: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
 6980: </form>
 6981: UPLOAD
 6982:     return '';
 6983: }
 6984: 
 6985: =pod
 6986: 
 6987: =item scantron_upload_scantron_data_save
 6988: 
 6989:    Adds a provided bubble information data file to the course if user
 6990:    has the correct privileges to do so.  
 6991: 
 6992: =cut
 6993: 
 6994: sub scantron_upload_scantron_data_save {
 6995:     my($r)=@_;
 6996:     my ($symb)=&get_symb($r,1);
 6997:     my $doanotherupload=
 6998: 	'<br /><form action="/adm/grades" method="post">'."\n".
 6999: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
 7000: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
 7001: 	'</form>'."\n";
 7002:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
 7003: 	!&Apache::lonnet::allowed('usc',
 7004: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
 7005: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
 7006: 	if ($symb) {
 7007: 	    $r->print(&show_grading_menu_form($symb));
 7008: 	} else {
 7009: 	    $r->print($doanotherupload);
 7010: 	}
 7011: 	return '';
 7012:     }
 7013:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
 7014:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
 7015:     my $fname=$env{'form.upfile.filename'};
 7016:     #FIXME
 7017:     #copied from lonnet::userfileupload()
 7018:     #make that function able to target a specified course
 7019:     # Replace Windows backslashes by forward slashes
 7020:     $fname=~s/\\/\//g;
 7021:     # Get rid of everything but the actual filename
 7022:     $fname=~s/^.*\/([^\/]+)$/$1/;
 7023:     # Replace spaces by underscores
 7024:     $fname=~s/\s+/\_/g;
 7025:     # Replace all other weird characters by nothing
 7026:     $fname=~s/[^\w\.\-]//g;
 7027:     # See if there is anything left
 7028:     unless ($fname) { return 'error: no uploaded file'; }
 7029:     my $uploadedfile=$fname;
 7030:     $fname='scantron_orig_'.$fname;
 7031:     if (length($env{'form.upfile'}) < 2) {
 7032: 	$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.");
 7033:     } else {
 7034: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
 7035: 	if ($result =~ m|^/uploaded/|) {
 7036: 	    $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
 7037: 	} else {
 7038: 	    $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>");
 7039: 	}
 7040:     }
 7041:     if ($symb) {
 7042: 	$r->print(&scantron_selectphase($r,$uploadedfile));
 7043:     } else {
 7044: 	$r->print($doanotherupload);
 7045:     }
 7046:     return '';
 7047: }
 7048: 
 7049: =pod
 7050: 
 7051: =item valid_file
 7052: 
 7053:    Validates that the requested bubble data file exists in the course.
 7054: 
 7055: =cut
 7056: 
 7057: sub valid_file {
 7058:     my ($requested_file)=@_;
 7059:     foreach my $filename (sort(&scantron_filenames())) {
 7060: 	if ($requested_file eq $filename) { return 1; }
 7061:     }
 7062:     return 0;
 7063: }
 7064: 
 7065: =pod
 7066: 
 7067: =item scantron_download_scantron_data
 7068: 
 7069:    Shows a list of the three internal files (original, corrected,
 7070:    skipped) for a specific bubble sheet data file that exists in the
 7071:    course.
 7072: 
 7073: =cut
 7074: 
 7075: sub scantron_download_scantron_data {
 7076:     my ($r)=@_;
 7077:     my $default_form_data=&defaultFormData(&get_symb($r,1));
 7078:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7079:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7080:     my $file=$env{'form.scantron_selectfile'};
 7081:     if (! &valid_file($file)) {
 7082: 	$r->print(<<ERROR);
 7083: 	<p>
 7084: 	    The requested file name was invalid.
 7085:         </p>
 7086: ERROR
 7087: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
 7088: 	return;
 7089:     }
 7090:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
 7091:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
 7092:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
 7093:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
 7094:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
 7095:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
 7096:     $r->print(<<DOWNLOAD);
 7097:     <p>
 7098: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
 7099:     </p>
 7100:     <p>
 7101: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
 7102:     </p>
 7103:     <p>
 7104: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
 7105:     </p>
 7106: DOWNLOAD
 7107:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
 7108:     return '';
 7109: }
 7110: 
 7111: =pod
 7112: 
 7113: =back
 7114: 
 7115: =cut
 7116: 
 7117: #-------- end of section for handling grading scantron forms -------
 7118: #
 7119: #-------------------------------------------------------------------
 7120: 
 7121: #-------------------------- Menu interface -------------------------
 7122: #
 7123: #--- Show a Grading Menu button - Calls the next routine ---
 7124: sub show_grading_menu_form {
 7125:     my ($symb)=@_;
 7126:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
 7127: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7128: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
 7129: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 7130: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
 7131: 	'</form>'."\n";
 7132:     return $result;
 7133: }
 7134: 
 7135: # -- Retrieve choices for grading form
 7136: sub savedState {
 7137:     my %savedState = ();
 7138:     if ($env{'form.saveState'}) {
 7139: 	foreach (split(/:/,$env{'form.saveState'})) {
 7140: 	    my ($key,$value) = split(/=/,$_,2);
 7141: 	    $savedState{$key} = $value;
 7142: 	}
 7143:     }
 7144:     return \%savedState;
 7145: }
 7146: 
 7147: sub grading_menu {
 7148:     my ($request) = @_;
 7149:     my ($symb)=&get_symb($request);
 7150:     if (!$symb) {return '';}
 7151:     my $probTitle = &Apache::lonnet::gettitle($symb);
 7152:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 7153: 
 7154:     #
 7155:     # Define menu data
 7156:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 7157:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 7158:     $request->print($table);
 7159:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
 7160:                   'handgrade'=>$hdgrade,
 7161:                   'probTitle'=>$probTitle,
 7162:                   'command'=>'submit_options',
 7163:                   'saveState'=>"",
 7164:                   'gradingMenu'=>1,
 7165:                   'showgrading'=>"yes");
 7166:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7167:     my @menu = ({ url => $url,
 7168:                      name => &mt('Manual Grading/View Submissions'),
 7169:                      short_description => 
 7170:     &mt('Start the process of hand grading submissions.'),
 7171:                  });
 7172:     $fields{'command'} = 'csvform';
 7173:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7174:     push (@menu, { url => $url,
 7175:                    name => &mt('Upload Scores'),
 7176:                    short_description => 
 7177:             &mt('Specify a file containing the class scores for current resource.')});
 7178:     $fields{'command'} = 'processclicker';
 7179:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7180:     push (@menu, { url => $url,
 7181:                    name => &mt('Process Clicker'),
 7182:                    short_description => 
 7183:             &mt('Specify a file containing the clicker information for this resource.')});
 7184:     $fields{'command'} = 'scantron_selectphase';
 7185:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7186:     push (@menu, { url => $url,
 7187:                    name => &mt('Grade Scantron Forms'),
 7188:                    short_description => 
 7189:             &mt('')});
 7190:     $fields{'command'} = 'verify';
 7191:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
 7192:     push (@menu, { url => "",
 7193:                    jscript => ' onClick="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" ',
 7194:                    name => &mt('Verify Receipt'),
 7195:                    short_description => 
 7196:             &mt('')});
 7197:     $fields{'command'} = 'manage';
 7198:     $url = &Apache::lonhtmlcommon::build_url('/adm/helper/resettimes.helper',\%fields);
 7199:     push (@menu, { url => $url,
 7200:                    name => &mt('Manage Access Times'),
 7201:                    short_description => 
 7202:             &mt('')});
 7203:     $fields{'command'} = 'view';
 7204:     $url = &Apache::lonhtmlcommon::build_url('/adm/pickcode',\%fields);
 7205:     push (@menu, { url => $url,
 7206:                    name => &mt('View Saved CODEs'),
 7207:                    short_description => 
 7208:             &mt('')});
 7209: 
 7210:     #
 7211:     # Create the menu
 7212:     my $Str;
 7213:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
 7214:     $Str .= '<form method="post" action="" name="gradingMenu">';
 7215:     $Str .= '<input type="hidden" name="command" value="" />'.
 7216:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7217: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 7218: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
 7219: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 7220: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 7221: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 7222: 
 7223:     foreach my $menudata (@menu) {
 7224:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
 7225:             $Str .='    <h3><a '.
 7226:                 $menudata->{'jscript'}.
 7227:                 ' href="'.
 7228:                 $menudata->{'url'}.'" >'.
 7229:                 $menudata->{'name'}."</a></h3>\n";
 7230:         } else {
 7231:             $Str .='    <h3><a '.
 7232:                 $menudata->{'jscript'}.
 7233:                 ' href="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" >'.
 7234:                 $menudata->{'name'}."</a></h3>\n";
 7235:             $Str .= ('&nbsp;'x8).
 7236:                     ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
 7237:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
 7238:         }
 7239:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
 7240:             "\n";
 7241:     }
 7242:     $Str .="</dl>\n";
 7243:     $Str .="</form>\n";
 7244:     $request->print(<<GRADINGMENUJS);
 7245: <script type="text/javascript" language="javascript">
 7246:     function checkChoice(formname,val,cmdx) {
 7247: 	if (val <= 2) {
 7248: 	    var cmd = radioSelection(formname.radioChoice);
 7249: 	    var cmdsave = cmd;
 7250: 	} else {
 7251: 	    cmd = cmdx;
 7252: 	    cmdsave = 'submission';
 7253: 	}
 7254: 	formname.command.value = cmd;
 7255: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 7256: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 7257: 	if (val < 5) formname.submit();
 7258: 	if (val == 5) {
 7259: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 7260: 	    formname.submit();
 7261: 	}
 7262: 	if (val < 7) formname.submit();
 7263:     }
 7264:     function checkChoice2(formname,val,cmdx) {
 7265: 	if (val <= 2) {
 7266: 	    var cmd = radioSelection(formname.radioChoice);
 7267: 	    var cmdsave = cmd;
 7268: 	} else {
 7269: 	    cmd = cmdx;
 7270: 	    cmdsave = 'submission';
 7271: 	}
 7272: 	formname.command.value = cmd;
 7273: 	if (val < 5) formname.submit();
 7274: 	if (val == 5) {
 7275: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 7276: 	    formname.submit();
 7277: 	}
 7278: 	if (val < 7) formname.submit();
 7279:     }
 7280: 
 7281:     function checkReceiptNo(formname,nospace) {
 7282: 	var receiptNo = formname.receipt.value;
 7283: 	var checkOpt = false;
 7284: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 7285: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 7286: 	if (checkOpt) {
 7287: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 7288: 	    formname.receipt.value = "";
 7289: 	    formname.receipt.focus();
 7290: 	    return false;
 7291: 	}
 7292: 	return true;
 7293:     }
 7294: </script>
 7295: GRADINGMENUJS
 7296:     &commonJSfunctions($request);
 7297:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
 7298:     $result.=$table;
 7299:     my (undef,$sections) = &getclasslist('all','0');
 7300:     my $savedState = &savedState();
 7301:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 7302:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 7303:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 7304:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 7305: 
 7306:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 7307: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7308: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 7309: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
 7310: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 7311: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 7312: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 7313: 
 7314:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
 7315: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
 7316: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
 7317: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
 7318: 
 7319:     $result.='<table width="100%" border="0">';
 7320:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
 7321:     $result.='<td><b>'.&mt('Sections').'</b></td>';
 7322: #    $result.='<td>Groups</td>';
 7323:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
 7324:     $result.='</tr>';
 7325:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
 7326: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
 7327:     if (ref($sections)) {
 7328: 	foreach (sort (@$sections)) {
 7329: 	    $result.='<option value="'.$_.'" '.
 7330: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
 7331: 	}
 7332:     }
 7333:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 7334:     return $Str;    
 7335: }
 7336: 
 7337: 
 7338: #--- Displays the submissions first page -------
 7339: sub submit_options {
 7340:     my ($request) = @_;
 7341:     my ($symb)=&get_symb($request);
 7342:     if (!$symb) {return '';}
 7343:     my $probTitle = &Apache::lonnet::gettitle($symb);
 7344: 
 7345:     $request->print(<<GRADINGMENUJS);
 7346: <script type="text/javascript" language="javascript">
 7347:     function checkChoice(formname,val,cmdx) {
 7348: 	if (val <= 2) {
 7349: 	    var cmd = radioSelection(formname.radioChoice);
 7350: 	    var cmdsave = cmd;
 7351: 	} else {
 7352: 	    cmd = cmdx;
 7353: 	    cmdsave = 'submission';
 7354: 	}
 7355: 	formname.command.value = cmd;
 7356: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
 7357: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
 7358: 	if (val < 5) formname.submit();
 7359: 	if (val == 5) {
 7360: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 7361: 	    formname.submit();
 7362: 	}
 7363: 	if (val < 7) formname.submit();
 7364:     }
 7365: 
 7366:     function checkReceiptNo(formname,nospace) {
 7367: 	var receiptNo = formname.receipt.value;
 7368: 	var checkOpt = false;
 7369: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
 7370: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
 7371: 	if (checkOpt) {
 7372: 	    alert("Please enter a receipt number given by a student in the receipt box.");
 7373: 	    formname.receipt.value = "";
 7374: 	    formname.receipt.focus();
 7375: 	    return false;
 7376: 	}
 7377: 	return true;
 7378:     }
 7379: </script>
 7380: GRADINGMENUJS
 7381:     &commonJSfunctions($request);
 7382:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
 7383:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
 7384:     $result.=$table;
 7385:     my (undef,$sections) = &getclasslist('all','0');
 7386:     my $savedState = &savedState();
 7387:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
 7388:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
 7389:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
 7390:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 7391: 
 7392:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 7393: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
 7394: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 7395: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
 7396: 	'<input type="hidden" name="command"     value="" />'."\n".
 7397: 	'<input type="hidden" name="saveState"   value="" />'."\n".
 7398: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
 7399: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 7400: 
 7401:     $result.='<table border="0"><tr><td bgcolor=#777777>'."\n".
 7402: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n".
 7403: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
 7404: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
 7405: 
 7406:     $result.='<table width="100%" border="0">';
 7407:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
 7408:     $result.='<td><b>'.&mt('Sections').'</b></td>';
 7409:     $result.='<td><b>'.&mt('Groups').'</b></td>';
 7410:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
 7411:     $result.='</tr>';
 7412:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
 7413: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
 7414:     if (ref($sections)) {
 7415: 	foreach (sort (@$sections)) {
 7416: 	    $result.='<option value="'.$_.'" '.
 7417: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
 7418: 	}
 7419:     }
 7420:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
 7421:     $result.= '</td><td>'."\n";
 7422:     $result.= &Apache::lonstatistics::GroupSelect('group','multiple',3);
 7423:     $result.='</td><td>'."\n";
 7424:     $result.=&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,3,undef,'mult');
 7425: 
 7426:     $result.='</td></tr>';
 7427: 
 7428:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3"><label>'.
 7429: 	'<input type="radio" name="radioChoice" value="submission" '.
 7430: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
 7431: 	'</label> <select name="submitonly">'.
 7432: 	'<option value="yes" '.
 7433: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
 7434: 	'<option value="queued" '.
 7435: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
 7436: 	'<option value="graded" '.
 7437: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
 7438: 	'<option value="incorrect" '.
 7439: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
 7440: 	'<option value="all" '.
 7441: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
 7442: 
 7443:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 7444: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
 7445: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
 7446: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
 7447: 
 7448:     $result.='<tr bgcolor="#ffffe6" valign="top"><td colspan="2">'.
 7449: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
 7450: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
 7451: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
 7452: 
 7453:     $result.='<tr bgcolor="#ffffe6"><td colspan="2"><br />'.
 7454: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
 7455: 	'</td></tr></table>'."\n";
 7456: 
 7457:     $result.='</td>'; #<td valign="top">';
 7458: 
 7459: #    $result.='<table width="100%" border="0">';
 7460: #    $result.='<tr bgcolor="#ffffe6"><td>'.
 7461: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
 7462: #	' '.&mt('scores from file').' </td></tr>'."\n";
 7463: #
 7464: #    $result.='<tr bgcolor="#ffffe6"><td>'.
 7465: #        '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
 7466: #        ' '.&mt('clicker file').' </td></tr>'."\n";
 7467: #
 7468: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 7469: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
 7470: #	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
 7471: #
 7472: #    if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
 7473: #	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
 7474: #	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
 7475: #	    ' '.&mt('receipt').': '.
 7476: #	    &Apache::lonnet::recprefix($env{'request.course.id'}).
 7477: #	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
 7478: #	    '</td></tr>'."\n";
 7479: #    } 
 7480: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 7481: #	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
 7482: #	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
 7483: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 7484: #	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
 7485: #	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
 7486: #
 7487: #    $result.='</table>'."\n".'</td>';
 7488:     $result.= '</tr></table>'."\n".
 7489: 	'</td></tr></table></form>'."\n";
 7490:     return $result;
 7491: }
 7492: 
 7493: sub reset_perm {
 7494:     undef(%perm);
 7495: }
 7496: 
 7497: sub init_perm {
 7498:     &reset_perm();
 7499:     foreach my $test_perm ('vgr','mgr','opa') {
 7500: 
 7501: 	my $scope = $env{'request.course.id'};
 7502: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
 7503: 
 7504: 	    $scope .= '/'.$env{'request.course.sec'};
 7505: 	    if ( $perm{$test_perm}=
 7506: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
 7507: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
 7508: 	    } else {
 7509: 		delete($perm{$test_perm});
 7510: 	    }
 7511: 	}
 7512:     }
 7513: }
 7514: 
 7515: sub gather_clicker_ids {
 7516:     my %clicker_ids;
 7517: 
 7518:     my $classlist = &Apache::loncoursedata::get_classlist();
 7519: 
 7520:     # Set up a couple variables.
 7521:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
 7522:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
 7523:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
 7524: 
 7525:     foreach my $student (keys(%$classlist)) {
 7526:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
 7527:         my $username = $classlist->{$student}->[$username_idx];
 7528:         my $domain   = $classlist->{$student}->[$domain_idx];
 7529:         my $clickers =
 7530: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
 7531:         foreach my $id (split(/\,/,$clickers)) {
 7532:             $id=~s/^[\#0]+//;
 7533:             $id=~s/[\-\:]//g;
 7534:             if (exists($clicker_ids{$id})) {
 7535: 		$clicker_ids{$id}.=','.$username.':'.$domain;
 7536:             } else {
 7537: 		$clicker_ids{$id}=$username.':'.$domain;
 7538:             }
 7539:         }
 7540:     }
 7541:     return %clicker_ids;
 7542: }
 7543: 
 7544: sub gather_adv_clicker_ids {
 7545:     my %clicker_ids;
 7546:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 7547:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7548:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
 7549:     foreach my $element (sort(keys(%coursepersonnel))) {
 7550:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
 7551:             my ($puname,$pudom)=split(/\:/,$person);
 7552:             my $clickers =
 7553: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
 7554:             foreach my $id (split(/\,/,$clickers)) {
 7555: 		$id=~s/^[\#0]+//;
 7556:                 $id=~s/[\-\:]//g;
 7557: 		if (exists($clicker_ids{$id})) {
 7558: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
 7559: 		} else {
 7560: 		    $clicker_ids{$id}=$puname.':'.$pudom;
 7561: 		}
 7562:             }
 7563:         }
 7564:     }
 7565:     return %clicker_ids;
 7566: }
 7567: 
 7568: sub clicker_grading_parameters {
 7569:     return ('gradingmechanism' => 'scalar',
 7570:             'upfiletype' => 'scalar',
 7571:             'specificid' => 'scalar',
 7572:             'pcorrect' => 'scalar',
 7573:             'pincorrect' => 'scalar');
 7574: }
 7575: 
 7576: sub process_clicker {
 7577:     my ($r)=@_;
 7578:     my ($symb)=&get_symb($r);
 7579:     if (!$symb) {return '';}
 7580:     my $result=&checkforfile_js();
 7581:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
 7582:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
 7583:     $result.=$table;
 7584:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
 7585:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
 7586:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
 7587:         '.</b></td></tr>'."\n";
 7588:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
 7589: # Attempt to restore parameters from last session, set defaults if not present
 7590:     my %Saveable_Parameters=&clicker_grading_parameters();
 7591:     &Apache::loncommon::restore_course_settings('grades_clicker',
 7592:                                                  \%Saveable_Parameters);
 7593:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
 7594:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
 7595:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
 7596:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
 7597: 
 7598:     my %checked;
 7599:     foreach my $gradingmechanism ('attendance','personnel','specific') {
 7600:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
 7601:           $checked{$gradingmechanism}="checked='checked'";
 7602:        }
 7603:     }
 7604: 
 7605:     my $upload=&mt("Upload File");
 7606:     my $type=&mt("Type");
 7607:     my $attendance=&mt("Award points just for participation");
 7608:     my $personnel=&mt("Correctness determined from response by course personnel");
 7609:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
 7610:     my $pcorrect=&mt("Percentage points for correct solution");
 7611:     my $pincorrect=&mt("Percentage points for incorrect solution");
 7612:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
 7613: 						   ('iclicker' => 'i>clicker',
 7614:                                                     'interwrite' => 'interwrite PRS'));
 7615:     $symb = &Apache::lonenc::check_encrypt($symb);
 7616:     $result.=<<ENDUPFORM;
 7617: <script type="text/javascript">
 7618: function sanitycheck() {
 7619: // Accept only integer percentages
 7620:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
 7621:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
 7622: // Find out grading choice
 7623:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 7624:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
 7625:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
 7626:       }
 7627:    }
 7628: // By default, new choice equals user selection
 7629:    newgradingchoice=gradingchoice;
 7630: // Not good to give more points for false answers than correct ones
 7631:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
 7632:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
 7633:    }
 7634: // If new choice is attendance only, and old choice was correctness-based, restore defaults
 7635:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
 7636:       document.forms.gradesupload.pcorrect.value=100;
 7637:       document.forms.gradesupload.pincorrect.value=100;
 7638:    }
 7639: // If the values are different, cannot be attendance only
 7640:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
 7641:        (gradingchoice=='attendance')) {
 7642:        newgradingchoice='personnel';
 7643:    }
 7644: // Change grading choice to new one
 7645:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
 7646:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
 7647:          document.forms.gradesupload.gradingmechanism[i].checked=true;
 7648:       } else {
 7649:          document.forms.gradesupload.gradingmechanism[i].checked=false;
 7650:       }
 7651:    }
 7652: // Remember the old state
 7653:    document.forms.gradesupload.waschecked.value=newgradingchoice;
 7654: }
 7655: </script>
 7656: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
 7657: <input type="hidden" name="symb" value="$symb" />
 7658: <input type="hidden" name="command" value="processclickerfile" />
 7659: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 7660: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 7661: <input type="file" name="upfile" size="50" />
 7662: <br /><label>$type: $selectform</label>
 7663: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
 7664: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
 7665: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
 7666: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
 7667: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
 7668: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
 7669: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
 7670: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
 7671: </form>
 7672: ENDUPFORM
 7673:     $result.='</td></tr></table>'."\n".
 7674:              '</td></tr></table><br /><br />'."\n";
 7675:     $result.=&show_grading_menu_form($symb);
 7676:     return $result;
 7677: }
 7678: 
 7679: sub process_clicker_file {
 7680:     my ($r)=@_;
 7681:     my ($symb)=&get_symb($r);
 7682:     if (!$symb) {return '';}
 7683: 
 7684:     my %Saveable_Parameters=&clicker_grading_parameters();
 7685:     &Apache::loncommon::store_course_settings('grades_clicker',
 7686:                                               \%Saveable_Parameters);
 7687: 
 7688:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 7689:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
 7690: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
 7691: 	return $result.&show_grading_menu_form($symb);
 7692:     }
 7693:     my %clicker_ids=&gather_clicker_ids();
 7694:     my %correct_ids;
 7695:     if ($env{'form.gradingmechanism'} eq 'personnel') {
 7696: 	%correct_ids=&gather_adv_clicker_ids();
 7697:     }
 7698:     if ($env{'form.gradingmechanism'} eq 'specific') {
 7699: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
 7700: 	   $correct_id=~tr/a-z/A-Z/;
 7701: 	   $correct_id=~s/\s//gs;
 7702: 	   $correct_id=~s/^[\#0]+//;
 7703:            $correct_id=~s/[\-\:]//g;
 7704:            if ($correct_id) {
 7705: 	      $correct_ids{$correct_id}='specified';
 7706:            }
 7707:         }
 7708:     }
 7709:     if ($env{'form.gradingmechanism'} eq 'attendance') {
 7710: 	$result.=&mt('Score based on attendance only');
 7711:     } else {
 7712: 	my $number=0;
 7713: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
 7714: 	foreach my $id (sort(keys(%correct_ids))) {
 7715: 	    $result.='<br /><tt>'.$id.'</tt> - ';
 7716: 	    if ($correct_ids{$id} eq 'specified') {
 7717: 		$result.=&mt('specified');
 7718: 	    } else {
 7719: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
 7720: 		$result.=&Apache::loncommon::plainname($uname,$udom);
 7721: 	    }
 7722: 	    $number++;
 7723: 	}
 7724:         $result.="</p>\n";
 7725: 	if ($number==0) {
 7726: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
 7727: 	    return $result.&show_grading_menu_form($symb);
 7728: 	}
 7729:     }
 7730:     if (length($env{'form.upfile'}) < 2) {
 7731:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
 7732: 		     '<span class="LC_error">',
 7733: 		     '</span>',
 7734: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
 7735:         return $result.&show_grading_menu_form($symb);
 7736:     }
 7737: 
 7738: # Were able to get all the info needed, now analyze the file
 7739: 
 7740:     $result.=&Apache::loncommon::studentbrowser_javascript();
 7741:     $symb = &Apache::lonenc::check_encrypt($symb);
 7742:     my $heading=&mt('Scanning clicker file');
 7743:     $result.=(<<ENDHEADER);
 7744: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 7745: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 7746: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 7747: <form method="post" action="/adm/grades" name="clickeranalysis">
 7748: <input type="hidden" name="symb" value="$symb" />
 7749: <input type="hidden" name="command" value="assignclickergrades" />
 7750: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
 7751: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
 7752: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
 7753: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
 7754: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
 7755: ENDHEADER
 7756:     my %responses;
 7757:     my @questiontitles;
 7758:     my $errormsg='';
 7759:     my $number=0;
 7760:     if ($env{'form.upfiletype'} eq 'iclicker') {
 7761: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
 7762:     }
 7763:     if ($env{'form.upfiletype'} eq 'interwrite') {
 7764:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
 7765:     }
 7766:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
 7767:              '<input type="hidden" name="number" value="'.$number.'" />'.
 7768:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
 7769:              '<input type="hidden" name="number" value="'.$number.'" />'.
 7770:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
 7771:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
 7772:              '<br />';
 7773: # Remember Question Titles
 7774: # FIXME: Possibly need delimiter other than ":"
 7775:     for (my $i=0;$i<$number;$i++) {
 7776:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
 7777:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
 7778:     }
 7779:     my $correct_count=0;
 7780:     my $student_count=0;
 7781:     my $unknown_count=0;
 7782: # Match answers with usernames
 7783: # FIXME: Possibly need delimiter other than ":"
 7784:     foreach my $id (keys(%responses)) {
 7785:        if ($correct_ids{$id}) {
 7786:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
 7787:           $correct_count++;
 7788:        } elsif ($clicker_ids{$id}) {
 7789:           if ($clicker_ids{$id}=~/\,/) {
 7790: # More than one user with the same clicker!
 7791:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
 7792:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 7793:                            "<select name='multi".$id."'>";
 7794:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
 7795:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
 7796:              }
 7797:              $result.='</select>';
 7798:              $unknown_count++;
 7799:           } else {
 7800: # Good: found one and only one user with the right clicker
 7801:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
 7802:              $student_count++;
 7803:           }
 7804:        } else {
 7805:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
 7806:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
 7807:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
 7808:                    "\n".&mt("Domain").": ".
 7809:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
 7810:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
 7811:           $unknown_count++;
 7812:        }
 7813:     }
 7814:     $result.='<hr />'.
 7815:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
 7816:     if ($env{'form.gradingmechanism'} ne 'attendance') {
 7817:        if ($correct_count==0) {
 7818:           $errormsg.="Found no correct answers answers for grading!";
 7819:        } elsif ($correct_count>1) {
 7820:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
 7821:        }
 7822:     }
 7823:     if ($number<1) {
 7824:        $errormsg.="Found no questions.";
 7825:     }
 7826:     if ($errormsg) {
 7827:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
 7828:     } else {
 7829:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
 7830:     }
 7831:     $result.='</form></td></tr></table>'."\n".
 7832:              '</td></tr></table><br /><br />'."\n";
 7833:     return $result.&show_grading_menu_form($symb);
 7834: }
 7835: 
 7836: sub iclicker_eval {
 7837:     my ($questiontitles,$responses)=@_;
 7838:     my $number=0;
 7839:     my $errormsg='';
 7840:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 7841:         my %components=&Apache::loncommon::record_sep($line);
 7842:         my @entries=map {$components{$_}} (sort(keys(%components)));
 7843: 	if ($entries[0] eq 'Question') {
 7844: 	    for (my $i=3;$i<$#entries;$i+=6) {
 7845: 		$$questiontitles[$number]=$entries[$i];
 7846: 		$number++;
 7847: 	    }
 7848: 	}
 7849: 	if ($entries[0]=~/^\#/) {
 7850: 	    my $id=$entries[0];
 7851: 	    my @idresponses;
 7852: 	    $id=~s/^[\#0]+//;
 7853: 	    for (my $i=0;$i<$number;$i++) {
 7854: 		my $idx=3+$i*6;
 7855: 		push(@idresponses,$entries[$idx]);
 7856: 	    }
 7857: 	    $$responses{$id}=join(',',@idresponses);
 7858: 	}
 7859:     }
 7860:     return ($errormsg,$number);
 7861: }
 7862: 
 7863: sub interwrite_eval {
 7864:     my ($questiontitles,$responses)=@_;
 7865:     my $number=0;
 7866:     my $errormsg='';
 7867:     my $skipline=1;
 7868:     my $questionnumber=0;
 7869:     my %idresponses=();
 7870:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
 7871:         my %components=&Apache::loncommon::record_sep($line);
 7872:         my @entries=map {$components{$_}} (sort(keys(%components)));
 7873:         if ($entries[1] eq 'Time') { $skipline=0; next; }
 7874:         if ($entries[1] eq 'Response') { $skipline=1; }
 7875:         next if $skipline;
 7876:         if ($entries[0]!=$questionnumber) {
 7877:            $questionnumber=$entries[0];
 7878:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
 7879:            $number++;
 7880:         }
 7881:         my $id=$entries[4];
 7882:         $id=~s/^[\#0]+//;
 7883:         $id=~s/^v\d*\://i;
 7884:         $id=~s/[\-\:]//g;
 7885:         $idresponses{$id}[$number]=$entries[6];
 7886:     }
 7887:     foreach my $id (keys %idresponses) {
 7888:        $$responses{$id}=join(',',@{$idresponses{$id}});
 7889:        $$responses{$id}=~s/^\s*\,//;
 7890:     }
 7891:     return ($errormsg,$number);
 7892: }
 7893: 
 7894: sub assign_clicker_grades {
 7895:     my ($r)=@_;
 7896:     my ($symb)=&get_symb($r);
 7897:     if (!$symb) {return '';}
 7898: # See which part we are saving to
 7899:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
 7900: # FIXME: This should probably look for the first handgradeable part
 7901:     my $part=$$partlist[0];
 7902: # Start screen output
 7903:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
 7904: 
 7905:     my $heading=&mt('Assigning grades based on clicker file');
 7906:     $result.=(<<ENDHEADER);
 7907: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
 7908: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
 7909: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
 7910: ENDHEADER
 7911: # Get correct result
 7912: # FIXME: Possibly need delimiter other than ":"
 7913:     my @correct=();
 7914:     my $gradingmechanism=$env{'form.gradingmechanism'};
 7915:     my $number=$env{'form.number'};
 7916:     if ($gradingmechanism ne 'attendance') {
 7917:        foreach my $key (keys(%env)) {
 7918:           if ($key=~/^form\.correct\:/) {
 7919:              my @input=split(/\,/,$env{$key});
 7920:              for (my $i=0;$i<=$#input;$i++) {
 7921:                  if (($correct[$i]) && ($input[$i]) &&
 7922:                      ($correct[$i] ne $input[$i])) {
 7923:                     $result.='<br /><span class="LC_warning">'.
 7924:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
 7925:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
 7926:                  } elsif ($input[$i]) {
 7927:                     $correct[$i]=$input[$i];
 7928:                  }
 7929:              }
 7930:           }
 7931:        }
 7932:        for (my $i=0;$i<$number;$i++) {
 7933:           if (!$correct[$i]) {
 7934:              $result.='<br /><span class="LC_error">'.
 7935:                       &mt('No correct result given for question "[_1]"!',
 7936:                           $env{'form.question:'.$i}).'</span>';
 7937:           }
 7938:        }
 7939:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
 7940:     }
 7941: # Start grading
 7942:     my $pcorrect=$env{'form.pcorrect'};
 7943:     my $pincorrect=$env{'form.pincorrect'};
 7944:     my $storecount=0;
 7945:     foreach my $key (keys(%env)) {
 7946:        my $user='';
 7947:        if ($key=~/^form\.student\:(.*)$/) {
 7948:           $user=$1;
 7949:        }
 7950:        if ($key=~/^form\.unknown\:(.*)$/) {
 7951:           my $id=$1;
 7952:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
 7953:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
 7954:           } elsif ($env{'form.multi'.$id}) {
 7955:              $user=$env{'form.multi'.$id};
 7956:           }
 7957:        }
 7958:        if ($user) { 
 7959:           my @answer=split(/\,/,$env{$key});
 7960:           my $sum=0;
 7961:           for (my $i=0;$i<$number;$i++) {
 7962:              if ($answer[$i]) {
 7963:                 if ($gradingmechanism eq 'attendance') {
 7964:                    $sum+=$pcorrect;
 7965:                 } else {
 7966:                    if ($answer[$i] eq $correct[$i]) {
 7967:                       $sum+=$pcorrect;
 7968:                    } else {
 7969:                       $sum+=$pincorrect;
 7970:                    }
 7971:                 }
 7972:              }
 7973:           }
 7974:           my $ave=$sum/(100*$number);
 7975: # Store
 7976:           my ($username,$domain)=split(/\:/,$user);
 7977:           my %grades=();
 7978:           $grades{"resource.$part.solved"}='correct_by_override';
 7979:           $grades{"resource.$part.awarded"}=$ave;
 7980:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
 7981:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
 7982:                                                  $env{'request.course.id'},
 7983:                                                  $domain,$username);
 7984:           if ($returncode ne 'ok') {
 7985:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
 7986:           } else {
 7987:              $storecount++;
 7988:           }
 7989:        }
 7990:     }
 7991: # We are done
 7992:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
 7993:              '</td></tr></table>'."\n".
 7994:              '</td></tr></table><br /><br />'."\n";
 7995:     return $result.&show_grading_menu_form($symb);
 7996: }
 7997: 
 7998: sub handler {
 7999:     my $request=$_[0];
 8000: 
 8001:     &reset_caches();
 8002:     if ($env{'browser.mathml'}) {
 8003: 	&Apache::loncommon::content_type($request,'text/xml');
 8004:     } else {
 8005: 	&Apache::loncommon::content_type($request,'text/html');
 8006:     }
 8007:     $request->send_http_header;
 8008:     return '' if $request->header_only;
 8009:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
 8010:     my $symb=&get_symb($request,1);
 8011:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
 8012:     my $command=$commands[0];
 8013: 
 8014:     if ($#commands > 0) {
 8015: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
 8016:     }
 8017: 
 8018: 
 8019:     $request->print(&Apache::loncommon::start_page('Grading'));
 8020:     if ($symb eq '' && $command eq '') {
 8021: 	if ($env{'user.adv'}) {
 8022: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
 8023: 		($env{'form.codethree'})) {
 8024: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
 8025: 		    $env{'form.codethree'};
 8026: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
 8027: 		    &Apache::lonnet::checkin($token);
 8028: 		if ($tsymb) {
 8029: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
 8030: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
 8031: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
 8032: 					  ('grade_username' => $tuname,
 8033: 					   'grade_domain' => $tudom,
 8034: 					   'grade_courseid' => $tcrsid,
 8035: 					   'grade_symb' => $tsymb)));
 8036: 		    } else {
 8037: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
 8038: 		    }
 8039: 		} else {
 8040: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
 8041: 		}
 8042: 	    } else {
 8043: 		$request->print(&Apache::lonxml::tokeninputfield());
 8044: 	    }
 8045: 	}
 8046:     } else {
 8047: 	&init_perm();
 8048: 	if ($command eq 'submission' && $perm{'vgr'}) {
 8049: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
 8050: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
 8051: 	    &pickStudentPage($request);
 8052: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
 8053: 	    &displayPage($request);
 8054: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
 8055: 	    &updateGradeByPage($request);
 8056: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
 8057: 	    &processGroup($request);
 8058: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
 8059: 	    $request->print(&grading_menu($request));
 8060: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
 8061: 	    $request->print(&submit_options($request));
 8062: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
 8063: 	    $request->print(&viewgrades($request));
 8064: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
 8065: 	    $request->print(&processHandGrade($request));
 8066: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
 8067: 	    $request->print(&editgrades($request));
 8068: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
 8069: 	    $request->print(&verifyreceipt($request));
 8070:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
 8071:             $request->print(&process_clicker($request));
 8072:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
 8073:             $request->print(&process_clicker_file($request));
 8074:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
 8075:             $request->print(&assign_clicker_grades($request));
 8076: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
 8077: 	    $request->print(&upcsvScores_form($request));
 8078: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
 8079: 	    $request->print(&csvupload($request));
 8080: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
 8081: 	    $request->print(&csvuploadmap($request));
 8082: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
 8083: 	    if ($env{'form.associate'} ne 'Reverse Association') {
 8084: 		$request->print(&csvuploadoptions($request));
 8085: 	    } else {
 8086: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
 8087: 		    $env{'form.upfile_associate'} = 'reverse';
 8088: 		} else {
 8089: 		    $env{'form.upfile_associate'} = 'forward';
 8090: 		}
 8091: 		$request->print(&csvuploadmap($request));
 8092: 	    }
 8093: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
 8094: 	    $request->print(&csvuploadassign($request));
 8095: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
 8096: 	    &Apache::lonnet::logthis("Selecting pyhase");
 8097: 	    $request->print(&scantron_selectphase($request));
 8098:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
 8099:  	    $request->print(&scantron_do_warning($request));
 8100: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
 8101: 	    $request->print(&scantron_validate_file($request));
 8102: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
 8103: 	    $request->print(&scantron_process_students($request));
 8104:  	} elsif ($command eq 'scantronupload' && 
 8105:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 8106: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 8107:  	    $request->print(&scantron_upload_scantron_data($request)); 
 8108:  	} elsif ($command eq 'scantronupload_save' &&
 8109:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
 8110: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
 8111:  	    $request->print(&scantron_upload_scantron_data_save($request));
 8112:  	} elsif ($command eq 'scantron_download' &&
 8113: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
 8114:  	    $request->print(&scantron_download_scantron_data($request));
 8115: 	} elsif ($command) {
 8116: 	    $request->print("Access Denied ($command)");
 8117: 	}
 8118:     }
 8119:     $request->print(&Apache::loncommon::end_page());
 8120:     &reset_caches();
 8121:     return '';
 8122: }
 8123: 
 8124: 1;
 8125: 
 8126: __END__;

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